Consider that code where I need to update the state after some data has been fetched, I just need to update the data portion of the initial state (clientData):
const [clientData, setClientData] = useState({
data: {},
product: 'profile'
});
useEffect(() => {
getProducts(1).then(res =>
setClientData({ ...clientData, data: res.data })
);
}, []);
How can I and is it possible to update just the "data" portion of the initial state without having to spread it (...clientData
)
This is not possible, seeing that the set method returned from the useState
hook replaces the prior state value with what ever you pass it, in it's entirety.
One possiblity would be to separate your state with multiple hooks which would give you a more granular means of updating your component's state:
/* Separate your state across multiple hooks */
const [data, setData] = useState({});
const [product, setProduct] = useState('profile');
useEffect(() => {
getProducts(1).then(res =>
/* Only update data portion of state via setData hook */
setData(res.data)
);
}, []);