useState
does not update the state immediately.
I'm using react-select and I need to load the component with the (multi
) options selected according to the result of the request.
For this reason, I created the state defaultOptions
, to store the value of the queues
constant.
It turns out that when loading the component, the values are displayed only the second time.
I made a console.log
in the queues
and the return is different from empty.
I did the same with the defaultOptions
state and the return is empty.
I created a codesandbox for better viewing.
const options = [
{
label: "Queue 1",
value: 1
},
{
label: "Queue 2",
value: 2
},
{
label: "Queue 3",
value: 3
},
{
label: "Queue 4",
value: 4
},
{
label: "Queue 5",
value: 5
}
];
const CustomSelect = (props) => <Select className="custom-select" {...props} />;
const baseUrl =
"https://my-json-server.typicode.com/wagnerfillio/api-json/posts";
const App = () => {
const userId = 1;
const initialValues = {
name: ""
};
const [user, setUser] = useState(initialValues);
const [defaultOptions, setDefaultOptions] = useState([]);
const [selectedQueue, setSelectedQueue] = useState([]);
useEffect(() => {
(async () => {
if (!userId) return;
try {
const { data } = await axios.get(`${baseUrl}/${userId}`);
setUser((prevState) => {
return { ...prevState, ...data };
});
const queues = data.queues.map((q) => ({
value: q.id,
label: q.name
}));
// Here there is a different result than emptiness
console.log(queues);
setDefaultOptions(queues);
} catch (err) {
console.log(err);
}
})();
return () => {
setUser(initialValues);
};
}, []);
// Here is an empty result
console.log(defaultOptions);
const handleChange = async (e) => {
const value = e.map((x) => x.value);
console.log(value);
setSelectedQueue(value);
};
return (
<div className="App">
Multiselect:
<CustomSelect
options={options}
defaultValue={defaultOptions}
onChange={handleChange}
isMulti
/>
</div>
);
};
export default App;
const {data} = await api.get ('/users/${userId}'
);` and after having the data I add the result to the statesetUserQueues
. I can't do it any other way, although I really tried. – Murphreeif (!userQueues) return <div>Loading</div>
or just nothing, so that there is no render with no info. You don't move the data to the first render. You move the first render to the data. – Stonwinqueues
defined for your return statement? – Glueyqueues
is declared hereconst queues = data.queues.map((q) => ({...
– Murphree