Cancelling my axios call on ReactJS but not working - javascript

I'm working on a project with graphs and I need to be able to cancel my requests if the user selects a different tab.
Here's my API call
export const getDifferentialData = (
sourceId: string,
sourceLine: string,
source: any
) => {
const graph1Request = getData(
sourceId,
sourceLine,
source
)
const graph2Request = getData(
sourceId,
sourceLine,
source
)
return Promise.all([graph1Request, graph2Request]).then(results => {
const [graphA, graphB] = results
return {
graphA: parsedData(graphA),
graphB: parsedData(graphB),
}
})
}
export const getData = (
sourceId: string,
sourceLine: string,
source?: any
) => {
if (sourceId && sourceLine) {
return api.get(`apiGoesHere`, { cancelToken: source.token }).then(response => {
const { data } = response
return parsedData(data)
})
} else {
return api.get(`apiGoesHere`, { cancelToken: source.token }).then(response => {
const { data } = response
return parsedData(data)
})
}
}
And the component where I'm doing the call. userDidChangeTab is called when pressing on a tab and it calls fetchGraph
const Graph: FC<Props> = () => {
const source = axios.CancelToken.source();
// we ensure that the query filters are up to date with the tab selected
const userDidChangeTab = (tabIndex: number) => {
const isDifferentialTabSelected = isDifferentialTab(tabIndex)
let newFilters = queryFilters
if (isDifferentialTabSelected) {
newFilters = {
// props go here
}
} else {
newFilters = {
// props go here
}
}
source.cancel()
fetchGraph(isDifferentialTabSelected)
setActiveTab(tabIndex)
}
// Function to fetch two differential graphs.
const fetchGraph = (isDifferential: boolean) => {
setFetching(true)
if (isDifferential) {
getDifferentialData(
sourceId,
sourceLine,
source
)
.then(({ graphA, graphB }: any) => {
setGraphData(graphA)
setMatchData(new diffMatch(graphA, graphB, 1.0))
})
.catch(reason => {
const errorMessage = errorMessageFromReason(reason)
addMessageToContainer(errorMessage, true)
})
.finally(() => {
setFetching(false)
})
} else {
getGraph(
sourceId,
sourceLine,
source
)
.then((graphData: any) => {
setGraphData(graphData)
setMatchData(null)
})
.catch(reason => {
const errorMessage = errorMessageFromReason(reason)
addMessageToContainer(errorMessage, true)
})
.finally(() => {
setFetching(false)
})
}
}
}

Related

How to Revalidate when data in fetcher is change using swr

I want to revalidate the date when on change. This is what I tried:
const fetchData = async() => {
const {
data
} = await axios.get(`/api/admin/orders${criteria}`, {
params: {
name: debouncedValue,
},
});
return data;
};
const {
data,
error: err,
mutate,
} = useSWR(`/api/admin/orders${criteria}/${nameSearch}`, fetchData);
const handleChange = (e: React.ChangeEvent < HTMLInputElement > ) => {
mutate();
setNameSearch(e.target.value);
};
But the data is no revalidate, I have to use the onTabFocus revalidation.

how to use response data as options for useInfiniteQuery

In the page where i wanna use useInfiniteQuery
const { data, error, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage, status } = useInfiniteQuery(
['posts', searchState],
({ pageParam = 1 }) => post.search({ ...searchState, pageParam }),
{
getNextPageParam: (lastPage, pages) => {
if (pages.length < 2) return pages.length + 1;
else return undefined;
},
},
);
This is my custom axios func:
export const post = {
search: async (params: { keyword: string; sort: string; region: string; pageParam: number }) => {
const { keyword, sort, region, pageParam } = params;
const sortValue = SortType[sort as keyof typeof SortType];
const url = `/post/search?keyword=${keyword}&page=${pageParam}&filter=${sortValue}&region=${region}`;
console.log(url);
const res = await client.get(url);
return res;
},
}
res in post.search function returns:
{"status":200,"message":"search success","data":{"posts":[],"pageCount":0}}
And I'd like to use pageCount as a condition for the getNextPageParam func, hasNextPage value.
What i really want to ask is, how can i use pageCount value in the following code:
getNextPageParam: (lastPage, pages) => {
For anyone who is not used to using react-query.
You can just simply look up the res.data using lastPage
const { data, error, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage, status } = useInfiniteQuery(
['posts', searchState],
async ({ pageParam = 1 }) => (await post.search({ searchState, pageParam })).data,
{
getNextPageParam: (lastPage, allPages) => {
if (lastPage === undefined) return undefined;
else return allPages.length < lastPage.pageCount && allPages.length + 1;
},
},
);

useEffect efficiency in Star Wars API

I need some help with me current project making in React. I'am making a star-wars-app for my job interview and I stucked on a one problem.
Fetch efficiency.
I'am fetching this data, and then fetching some more because of the url's in the first fetched data, and everything fetches good, but first i have the 'url's' seeing in the table and then it changes into correct data.
I want to set the 'fetched' state to true when everything is rendered correctly but I don't know how to do it.
const api = `https://swapi.dev/api/people/`;
const [characters, setCharacters] = useState([]);
const [speciesOptions, setSpeciesOptions] = useState([]);
const [homeworldOptions, setHomeworldOptions] = useState([]);
const [fetched, setFetched] = useState(false);
useEffect(() => {
const fetchedTimeout = () => {
setTimeout(() => {
setFetched(true);
}, 2000);
};
const fetchArray = (array, arrName) => {
for (let elem of array) {
fetch(elem).then((response) =>
response.json().then((data) => {
array.shift();
array.push(data.name);
})
);
}
if (arrName === "species") {
if (!array.length) {
array.push("Unspecified");
}
}
};
async function fetchOtherData(characters) {
await characters.forEach((character) => {
const homeworld = character.homeworld;
const vehicles = character.vehicles;
const starships = character.starships;
const species = character.species;
fetch(homeworld).then((response) =>
response.json().then((data) =>
setCharacters((prevData) =>
prevData.map((prevCharacter) =>
prevCharacter.homeworld === homeworld
? {
...prevCharacter,
homeworld: data.name,
}
: prevCharacter
)
)
)
);
fetchArray(vehicles);
fetchArray(starships);
fetchArray(species, "species");
});
await setCharacters(characters);
await fetchedTimeout();
}
const fetchAllCharacters = (allCharacters, data) => {
if (data.next) {
fetch(data.next)
.then((response) => response.json())
.then((data) => {
allCharacters.push(...data.results);
fetchAllCharacters(allCharacters, data);
});
}
if (!data.next) {
fetchOtherData(allCharacters);
}
};
async function fetchApi() {
const allCharacters = [];
await fetch(api)
.then((response) => response.json())
.then((data) => {
allCharacters.push(...data.results);
fetchAllCharacters(allCharacters, data);
})
.catch((error) => console.log(error));
}
const setSpeciesFiltering = () => {
const speciesFiltering = [];
for (let character of characters) {
const characterSpecies = character.species.join();
const foundSpecies = speciesFiltering.indexOf(characterSpecies);
if (foundSpecies === -1) {
speciesFiltering.push(characterSpecies);
}
}
const speciesOptions = speciesFiltering.map((species) => (
<option value={species}>{species}</option>
));
setSpeciesOptions(speciesOptions);
};
const setHomeworldFiltering = () => {
const homeworldFiltering = [];
for (let character of characters) {
const characterHomeworld = character.homeworld;
const foundSpecies =
homeworldFiltering.indexOf(characterHomeworld);
if (foundSpecies === -1) {
homeworldFiltering.push(characterHomeworld);
}
}
const homeworldOptions = homeworldFiltering.map((homeworld) => (
<option value={homeworld}>{homeworld}</option>
));
setHomeworldOptions(homeworldOptions);
};
fetchApi();
setSpeciesFiltering();
setHomeworldFiltering();
}, []);
I will appreciate your response.
Okay, after all the comments (thanks for that!) i changed the code to something like this.
useEffect(() => {
const fetchOtherData = (characters) => {
const charactersWithAllData = [];
characters.forEach((character) => {
const homeworld = character.homeworld;
const species = character.species;
const vehicles = character.vehicles;
const starships = character.starships;
let urls = [homeworld, ...species, ...vehicles, ...starships];
Promise.all(
urls.map((url) => {
if (url.length) {
fetch(url)
.then((response) => response.json())
.then((data) => {
if (url.search("species") > 0) {
character.species = data.name;
}
if (url.search("planets") > 0) {
character.homeworld = data.name;
}
if (url.search("vehicles") > 0) {
character.vehicles.shift();
character.vehicles.push(data.name);
}
if (url.search("starships") > 0) {
character.starships.shift();
character.starships.push(data.name);
}
})
.catch((err) => console.error(err));
}
if (!url.length) {
if (url.search("species")) {
character.species = "Unspecified";
}
if (url.search("vehicles")) {
character.vehicles = "";
}
if (url.search("starships")) {
character.starships = "";
}
}
})
).then(charactersWithAllData.push(character));
});
return charactersWithAllData;
};
const fetchApi = () => {
const characters = [];
Promise.all(
[api].map((api) =>
fetch(api)
.then((response) => response.json())
.then((data) => characters.push(...data.results))
.then((data) => {
setCharacters(fetchOtherData(characters));
})
)
);
};
fetchApi();
}, []);
In what point do i have to set the 'characters' state ? Because in the situation above the data first shows on the screen, and then the state is set.
As other comments say, using Promise.all and refactoroing your useEffect is best solution for this.
But this might be helpful if you don't want to change a lot.
(but still consider refactor your hook)
const [loading, setLoading] = useState(0);
const isLoading = loading > 0;
// replace your fetches with below:
const myFetch = async (path) => {
try {
setLoading(loading => loading + 1);
return await fetch(path);
} finally {
setLoading(loading => loading - 1);
}
};
useEffect(() => {
// do your stuffs
}, []);

Objects in array are empty when return statement is included in function

I have a function that I want to return the array of objects parsedContacts. With the return statement there, the console.log above it prints an array of empty objects. When I remove the return statement, each object has three properties as expected.
How can I return the parsedContacts and include the properties?
/* eslint-disable no-console */
/* eslint-disable no-unused-vars */
import { PermissionsAndroid } from 'react-native';
import Contacts from 'react-native-contacts';
export const getAndProcessPhoneContacts = async () => {
PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.READ_CONTACTS,
{
'title': 'Contacts',
'message': 'Xxxxxxxx would like to view your contacts.'
}
)
const contacts = await getContacts();
const parsedContacts = parseContacts(contacts);
sortContacts(parsedContacts);
console.log(parsedContacts);
return parsedContacts; // this line needs to be removed for parsedContacts to have properties in the objects inside it.
}
const getContacts = () => {
return new Promise((resolve, reject) => {
Contacts.getAll((error, contacts) => {
contacts ? resolve(contacts) : reject(error)
})
})
}
const parseContacts = contacts => {
return contacts.map(contact => {
let parsedContact = {}
Object.keys(contact).forEach(key => {
switch (key) {
case 'givenName':
parsedContact.firstName = contact[key]
break
case 'familyName':
parsedContact.surname = contact[key]
break
case 'phoneNumbers':
parsedContact.phoneNumber = contact[key].length ? contact[key][0].number : ''
}
})
return parsedContact
})
}
const sortContacts = contacts => {
contacts.sort((a, b) => {
let contactA = a.firstName;
let contactB = b.firstName;
return (contactA < contactB) ? -1 : (contactA > contactB) ? 1 : 0;
});
}
Update
As requested in the comments below, here is the calling function of getAndProcessPhoneContacts. I know that this is ugly and needs refactoring, any advice on this gratefully accepted too!
async componentDidMount() {
ConnectyCube.init(...config)
try {
const accessToken = await getFirebaseToken();
if (accessToken) {
await authorizeConnectyCube(accessToken);
if (this.props.user.parsedContacts) {
const registeredUsers = await retrieveRegisteredUsers();
this.props.updateRegisteredContacts(registeredUsers);
Actions.Dashboard();
} else {
const parsedContacts = await getParsedContactsFromStorage();
if (parsedContacts) {
this.props.updateParsedContacts(parsedContacts);
Actions.Dashboard();
} else {
const parsedContacts = await getAndProcessPhoneContacts();
console.log(parsedContacts); // prints an array of empty objects
await writeParsedContactsToStorage(parsedContacts);
this.props.updateParsedContacts(parsedContacts);
const registeredUsers = await retrieveRegisteredUsers();
this.props.updateRegisteredContacts(registeredUsers);
Actions.Dashboard();
}
}
} else {
Actions.PhoneNumberInput();
}
} catch (error) {
Alert.alert(error);
}
}
Update 2
I have an inelegant solution by using a callback:
const cb = (ct) => {
console.log(ct); // Objects now have properties
}
const parsedContacts = await getAndProcessPhoneContacts(cb);
await writeParsedContactsToStorage(parsedContacts);
this.props.updateParsedContacts(parsedContacts);
const registeredUsers = await retrieveRegisteredUsers();
this.props.updateRegisteredContacts(registeredUsers);
Actions.Dashboard();
}
}
} else {
Actions.PhoneNumberInput();
}
} catch (error) {
Alert.alert(error);
}
}
And the called function:
export const getAndProcessPhoneContacts = async (cb) => {
PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.READ_CONTACTS,
{
'title': 'Contacts',
'message': 'Xxxxxxx would like to view your contacts.'
}
)
const contacts = await getContacts();
const parsedContacts = parseContacts(contacts);
sortContacts(parsedContacts);
console.log(parsedContacts);
cb(parsedContacts)
}

Why am I unable to re-add data with the same name after removing it with Firebase?

In my app, users are able to add a loved one, like so:
addLovedOne(event) {
const {
lovedOne,
} = this.state;
const unsubscribe = firebase.auth().onAuthStateChanged((user) => {
if (user) {
db.addLovedOne(user.uid, lovedOne)
.then(() => {
this.setState({ lovedOne: '' });
this.refreshLovedOnes();
})
.catch(error => {
this.setState(byPropKey('error', error));
});
} else {
unsubscribe();
}
});
event.preventDefault();
}
Naturally, users are able to remove loved ones, like so:
removeLovedOne(event) {
const lovedOne = event.target.id;
const unsubscribe = firebase.auth().onAuthStateChanged((user) => {
if (user) {
const ref = firebase.database().ref(`users/${user.uid}/lovedOnes`);
const removeLovedOne = ref.orderByChild('lovedOne').equalTo(lovedOne);
removeLovedOne.on('value', (snapshot) => {
const lovedOneId = snapshot.node_.children_.root_.key;
db.removeLovedOne(user.uid, lovedOneId, lovedOne)
.then(() => {
this.refreshLovedOnes();
})
.catch(error => {
this.setState(byPropKey('error', error));
});
});
} else {
unsubscribe();
}
});
}
Here is what the queries look like:
export const addLovedOne = (userId, lovedOne) => (
db.ref(`users/${userId}/lovedOnes`).push({
lovedOne,
})
);
export const removeLovedOne = (userId, lovedOneKey) => (
db.ref(`users/${userId}/lovedOnes/${lovedOneKey}/lovedOne`).remove()
);
Here is what my schema looks like:
Any idea why I'm not able to add a loved one with the same name after removing it without refreshing the page?

Categories