useState is not updating inside array.map(). ReactJS - arrays

I am trying to add the values of an array by using useState inside an array.map but the values are not updating
function App() {
const [ingredients, setIngredients] = useState([]);
const getIngredients = (data) => {
data.map((item, i) => {
console.log(data[i]);
setIngredients([...ingredients, data[i]]);
// setIngredients([...ingredients, item]); <- Also doesnt work
console.log(ingredients);
});
Console.log(data)
(26) ["Product", "Information↵NUTELLA", "HAZELNUT", "SPREAD", "↵Total:", "↵aty:", "↵BARILLA", "SPAGHETTI", "Z↵Total:", "↵CLASSICO", "CRMY", "ALFERO", "DI", "ROMA", "PENNE", "RIGATE", "PASTA", "↵Order", "Summary↵item", "Subtotat", "↵Sales", "Tax", "Total:", "", "↵", Array(0)]
console.log(ingredients);
[]
console.log(items);
Lists out all the items one after the other

setState is asynchronous so it doesn't guarantee an updated state from before, so pass a function to setState to make it work.
setIngredients((ingredients) => [...ingredients, data[i]]);

Related

State not updating inside async function in useEffect

Expected:
Following useEffect fetches a list of pool addresses when first rendered and assigns it to getPoolsList, which should then be used to set poolsList state.
const [poolsList, setPoolsList] = useState([]);
useEffect(() => {
async function fetchPools() {
const getPoolsList = await discountmain.methods.allPool().call();
console.log(getPoolsList); //returns ['0x...']
setPoolsList(getPoolsList);
}
fetchPools();
}, []);
The following code I added to check the value of poolsList whenever its value changes.
useEffect(() => {
console.log("useeffect", poolsList); // returns []
}, [poolsList]);
However, poolsList is showing [].
The file is https://codeshare.io/j0wBLD.
What am I doing wrong? I'm a newbie in React.
Your code looks fine, but React can be finicky with arrays in the dependency array
First thing is to actually make sure that the data changes and the useEffect hook is not being called
Here are few things you can try:
Probably the best solution: useReducer
Use the array length and watch the length
const [poolsList, setPoolsList] = useState([]);
const [poolsListLength, setPoolListLength] = useState(0);
useEffect(() => {
async function fetchPools() {
const getPoolsList = await discountmain.methods.allPool().call();
console.log(getPoolsList); //returns ['0x...']
setPoolsList(getPoolsList);
setPoolListLength(getPoolList.length)
}
fetchPools();
}, []);
then
useEffect(() => {
console.log("useeffect", poolsList); // returns []
}, [poolsListLength]);
Use Set
Not my favorite, but you can Stringify the array
useEffect(() => {
console.log(outcomes)
}, [JSON.stringify(outcomes)])

React calling function using useEffect multiple time

I tried to calling a function more then 2 times using useEffect hook but the result it only calling that function with last call.
here is my code and try :
const [ selectValues, setSelectValues ] = useState([]);
const selectHandler = (e) => {
const filteredValues = selectValues.filter((i) => i.id !== e.id);
setSelectValues([ ...filteredValues, e ]);
};
useEffect(() => {
const obj1 = {...}
const obj2 = {...}
selectHandler(obj1)
selectHandler(obj2) // this is the only object will be saved to the state
},[])
I hope that issue explained properly
To be able to save any intermediate values from the state, you should update it in a callback manner, because selectValues contains the value which was there when component was rendered (initial value in our case).
const selectHandler = (e) => {
setSelectValues((prevValues) => [...prevValues.filter((i) => i.id !== e.id), e]);
};

Infinite recursion using React Hooks

I am using React's State Hook in a functional component for getting therapist from database. From which I seen, in useEffect() where setTherapists([therapists].concat(therapists)); is, the list is called in an infinite recursion. I can't see where the problems is, or how do I need to proper call the list.
After I correct get the therapists array I need to render all the therapist. This is how I thought about, but I don't know exactly how to write with Hooks State:
function renderTherapists() {
const items = this.state.therapists.map( (t, idx) => (
<TherapistCard therapist={t} key={idx} />
))
return (
<div ref={0} className="therapist-list">
{ items }
</div>
)
}
My current functional component:
function TypeArticleOne(props) {
const [ therapists, setTherapists ]= useState([]);
const [speciality, setSpeciality]= useState('ABA');
const [pageLoading, setPageLoading]= useState(true);
const topProfilesUrl = 'therapists/top/profiles'
useEffect(() => {
console.log(speciality);
getTopTherapists();
window.scrollTo(0, 0);
}, []);
const getTopTherapists = () => {
setPageLoading(true);
loadTopTherapists();
};
const loadTopTherapists = () => {
console.log("second");
props.actions.reqGetTherapistsTopProfiles({
body: {},
headers: null,
resource: `${topProfilesUrl}`
})
};
useEffect(() => {
let apiData = props.apiData;
if (apiData.topProfiles && apiData.topProfiles.success) {
const therapists = apiData.topProfiles.therapists;
setPageLoading(false);
setTherapists([therapists].concat(therapists));
}
}, [pageLoading, therapists]);
You need to pass the Therapists coming in the props to the default value of your useState declaration:
const [ therapists, setTherapists ] = useState(apiData.topProfiles.therapists);
So when it's re-rendered, it doesn't get called again in a loop.
The constant therapists is shadowing the therapist list from your outer scope.
if (apiData.topProfiles && apiData.topProfiles.success) {
const therapists = apiData.topProfiles.therapists;
setPageLoading(false);
setTherapists([therapists].concat(therapists));
}
Also, as it's already an array, you can call the concat method without put the list within brackets [].
Like:
const loadedTherapists = apiData.topProfiles.therapists;
setPageLoading(false);
setTherapists(therapists.concat(loadedTherapists));

React useEffect dependency of useCallback always triggers render

I have a mystery. Consider the following custom React hook that fetches data by time period and stores the results in a Map:
export function useDataByPeriod(dateRanges: PeriodFilter[]) {
const isMounted = useMountedState();
const [data, setData] = useState(
new Map(
dateRanges.map(dateRange => [
dateRange,
makeAsyncIsLoading({ isLoading: false }) as AsyncState<MyData[]>
])
)
);
const updateData = useCallback(
(period: PeriodFilter, asyncState: AsyncState<MyData[]>) => {
const isSafeToSetData = isMounted === undefined || (isMounted !== undefined && isMounted());
if (isSafeToSetData) {
setData(new Map(data.set(period, asyncState)));
}
},
[setData, data, isMounted]
);
useEffect(() => {
if (dateRanges.length === 0) {
return;
}
const loadData = () => {
const client = makeClient();
dateRanges.map(dateRange => {
updateData(dateRange, makeAsyncIsLoading({ isLoading: true }));
return client
.getData(dateRange.dateFrom, dateRange.dateTo)
.then(periodData => {
updateData(dateRange, makeAsyncData(periodData));
})
.catch(error => {
const errorString = `Problem fetching ${dateRange.displayPeriod} (${dateRange.dateFrom} - ${dateRange.dateTo})`;
console.error(errorString, error);
updateData(dateRange, makeAsyncError(errorString));
});
});
};
loadData();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [dateRanges /*, updateData - for some reason when included this triggers infinite renders */]);
return data;
}
The useEffect is being repeatedly triggered when updateData is added as a dependency. If I exclude it as a dependency then everything works / behaves as expected but eslint complains I'm violating react-hooks/exhaustive-deps.
Given updateData has been useCallback-ed I'm at a loss to understand why it should repeatedly trigger renders. Can anyone shed any light please?
The problem lies in the useCallback/useEffect used in combination. One has to be careful with dependency arrays in both useCallback and useEffect, as the change in  the useCallback dependency array will trigger the useEffect to run. 
The “data” variable is used inside useCallback dependency array, and when the setData is called react will rerun function component with new value for data variable and that triggers a chain of calls. 
Call stack would look something like this:
useEffect run
updateData called
setState called
component re-renders with new state data
new value for data triggers useCallback
updateData changed
triggers useEffect again
To solve the problem you would need to remove the “data” variable from the useCallback dependency array. I find it to be a good practice to not include a component state in the dependency arrays whenever possible.
If you need to change component state from the useEffect or useCallback and the new state is a function of the previous state, you can pass the function that receives a current state as parameter and returns a new state.
const updateData = useCallback(
(period: PeriodFilter, asyncState: AsyncState<MyData[]>) => {
const isSafeToSetData = isMounted === undefined || (isMounted !== undefined && isMounted());
if (isSafeToSetData) {
setData(existingData => new Map(existingData.set(period, asyncState)));
}
},
[setData, isMounted]
);
In your example you need the current state only to calculate next state so that should work.
This is what I now have based on #jure's comment above:
I think the problem is that the "data" variable is included in the dependency array of useCallback. Every time you setData, the data variable is changed that triggers useCallback to provide new updateData and that triggers useEffect. Try to implement updateData without a dependecy on the data variable. you can do something like setData(d=>new Map(d.set(period, asyncState)) to avoid passing "data" variable to useCallback
I adjusted my code in the manners suggested and it worked. Thanks!
export function useDataByPeriod(dateRanges: PeriodFilter[]) {
const isMounted = useMountedState();
const [data, setData] = useState(
new Map(
dateRanges.map(dateRange => [
dateRange,
makeAsyncIsLoading({ isLoading: false }) as AsyncState<MyData[]>
])
)
);
const updateData = useCallback(
(period: PeriodFilter, asyncState: AsyncState<MyData[]>) => {
const isSafeToSetData = isMounted === undefined || (isMounted !== undefined && isMounted());
if (isSafeToSetData) {
setData(existingData => new Map(existingData.set(period, asyncState)));
}
},
[setData, isMounted]
);
useEffect(() => {
if (dateRanges.length === 0) {
return;
}
const loadData = () => {
const client = makeClient();
dateRanges.map(dateRange => {
updateData(dateRange, makeAsyncIsLoading({ isLoading: true }));
return client
.getData(dateRange.dateFrom, dateRange.dateTo)
.then(traffic => {
updateData(dateRange, makeAsyncData(traffic));
})
.catch(error => {
const errorString = `Problem fetching ${dateRange.displayPeriod} (${dateRange.dateFrom} - ${dateRange.dateTo})`;
console.error(errorString, error);
updateData(dateRange, makeAsyncError(errorString));
});
});
};
loadData();
}, [dateRanges , updateData]);
return data;
}

React Hooks - Ref is not available inside useEffect

I am using ReactHooks. I am trying to access ref of User component in useEffect function, but I am getting elRef.current value as null, though I passed elRef.current as second argument to useEffect. I am supposed to get reference to an element, but outside (function body) of useEffect, ref value is available. Why is that ? How can I get elRef.current value inside useEffect?
code
import React, { Component, useState, useRef, useEffect } from "react";
const useFetch = url => {
const [data, setData] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
useEffect(
() => {
setIsLoading(true);
fetch(url)
.then(response => {
if (!response.ok) throw Error(response.statusText);
return response.json();
})
.then(json => {
setIsLoading(false);
setData(json.data);
})
.catch(error => {
setIsLoading(false);
setError(error);
});
},
[url]
);
return { data, isLoading, error };
};
const User = ({ id }) => {
const elRef = useRef(null);
const { data: user } = useFetch(`https://reqres.in/api/users/${id}`);
useEffect(() => {
console.log("ref", elRef.current);
}, [elRef.current]);
if (!user) return null;
return <div ref={elRef}>{user.first_name + " " + user.last_name}</div>;
};
class App extends Component {
state = {
userId: 1
};
handleNextClick = () => {
this.setState(prevState => ({
userId: prevState.userId + 1
}));
};
handlePrevNext = () => {
this.setState(prevState => ({
userId: prevState.userId - 1
}));
};
render() {
return (
<div>
<button
onClick={() => this.handlePrevClick()}
disabled={this.state.userId === 1}
>
Prevoius
</button>
<button onClick={() => this.handleNextClick()}>Next</button>
<User id={this.state.userId} />
</div>
);
}
}
export default App;
Codesandbox link
Thanks !
You should use useCallback instead of useRef as suggested in the reactjs docs.
React will call that callback whenever the ref gets attached to a different node.
Replace this:
const elRef = useRef(null);
useEffect(() => {
console.log("ref", elRef.current);
}, [elRef.current]);
with this:
const elRef = useCallback(node => {
if (node !== null) {
console.log("ref", node); // node = elRef.current
}
}, []);
It's a predictable behaviour.
As mentioned #estus you faced with this because first time when it's called on componentDidMount you're getting null (initial value) and get's updated only once on next elRef changing because, actually, reference still being the same.
If you need to reflect on every user change, you should pass [user] as second argument to function to make sure useEffect fired when user is changed.
Here is updated sandbox.
Hope it helped.
When you use a function as a ref, it is called with the instance when it is ready. So the easiest way to make the ref observable is to use useState instead of useRef:
const [element, setElement] = useState<Element | null>(null);
return <div ref={setElement}></div>;
Then you can use it in dependency arrays for other hooks, just like any other const value:
useEffect(() => {
if (element) console.log(element);
}, [element]);
See also How to rerender when refs change.
useEffect is used as both componentDidMount and componentDidUpdate,
at the time of component mount you added a condition:
if (!user) return null;
return <div ref={elRef}>{user.first_name + " " + user.last_name}</div>;
because of the above condition at the time of mount, you don't have the user, so it returns null and div is not mounted in the DOM in which you are adding ref, so inside useEffect you are not getting elRef's current value as it is not rendered.
And on the click of next as the div is mounted in the dom you got the value of elRef.current.
The assumption here is that useEffect needs to detect changes to ref.current, so needs to have the ref or ref.currentin the dependencies list. I think this is due to es-lint being a bit over-pedantic.
Actually, the whole point of useEffect is that it guarantees not to run until the rendering is complete and the DOM is ready to go. That is how it handles side-effects.
So by the time useEffect is executed, we can be sure that elRef.current is set.
The problem with your code is that you don't run the renderer with <div ref={elRef}...> until after user is populated. So the DOM node you want elRef to reference doesn't yet exist. That is why you get the null logging - nothing to do with dependencies.
BTW: one possible alternative is to populate the div inside the effect hook:
useEffect(
() => {
if(!user) return;
elRef.current.innerHTML = `${user.first_name} ${user.last_name}`;
}, [user]
);
...
//if (!user) return null;// Remove this line
return <div ref={elRef}></div>; //return div every time.
That way the if (!user) return null; line in the User component is unnecessary. Remove it, and elRef.current is guaranteed to be populated with the div node from the very beginning.
set a useEffect on the elem's.current:
let elem = useRef();
useEffect(() => {
// ...
}, [elem.current]);

Resources