I am using useState to set a state I have collected data in two different states (that are text and inputs ) now I want to add both states into a third state (that is alldata)
I have tried
const [alldata, setAlldata] = useState({})
const [text, setText] = useState({ category: "product", });// there is more than one value
const [inputs, setInputs] = useState([
{ item: "", quantity: "", rate: "", tax: "" },
]);
setAlldata(
{
"text":text,
"inputs":inputs,
}
)
console.log(alldata)
but it's giving an empty object I want text and inputs in alldata that should look like
alldata:{
text:{},
inputs:{},
}
please suggest me any other way
The setState
is asynchronous, meaning the value will only be reflected on next render. Here's the detailed answer that dives deep into this behavior.
However, it could be an XY problem. If alldata
purly depends on other states, using a useMemo
would be preferred. It reflects the changes automatically when either of the states is mutated.
const [text, setText] = useState({ category: "product", });// there is more than one value
const [inputs, setInputs] = useState([
{ item: "", quantity: "", rate: "", tax: "" },
]);
const alldata = useMemo(() => ({ text, inputs }), [text, inputs]);
console.log(alldata); // { text: { /* ... */ }, inputs: { /* ... */} }