I'm new to learning React (without backend, with Context API). In the Context Provider, I'm looking for a way to set two Hook states from the same data. To make a single axios call (without re-rendering). The Provider takes in App. Are there any solutions?
export const Context = React.createContext();
const MoviesProvider = ({ children }) => {
console.log("Context Affectations");
const [movies, setMovies] = React.useState(null);
const [selectedMovie, setSelectedMovie] = React.useState(null);
useEffect(() => {
console.log("Context useEffect 1");
const dataGet = externalData;
setMovies(dataGet);
});
useEffect(() => {
console.log("Context useEffect 2");
// SKIPPED PART
const dataGet = externalData;
setSelectedMovie(dataGet[0]);
// SKIPPED PART
});
Tried both in the same useEffect, the second is skipped too.
Console:
Context Affectations
Context useEffect 1
Pass data
Context useEffect 2
Context Affectations
So first of all you should do a quick read on useEffect's
dependency array and why is super useful article. What you are trying to solve can be achieved with one useEffect without issues.
useEffect(() => {
console.log("Context useEffect 2");
// SKIPPED PART
const dataGet = externalData;
setMovies(dataGet);
setSelectedMovie(dataGet[0]);
// SKIPPED PART
}, []); // <- Important part this empty array means that this will run only at the mount of the component (first time appearing) but you could put inside the variable to watch so every time that changes it fetches again