I am trying to update the array using useEffect + useState.
const CategorySearch = (props) => {
const initialValue = [
{
value: '',
name: '',
},
];
const [options, setOptions] = useState(initialValue);
const updateOptions = () => {
let convert = [];
for (const options of props.categories) {
convert.push({ value: options._id, label: options.name });
}
console.log(convert);
setOptions(convert);
console.log(options);
};
useEffect(() => {
updateOptions();
console.log(props.categories);
}, [props.categories]);
return (
.......
);
};
const mapStateToProps = ({ categories }) => ({
categories,
});
export default connect(mapStateToProps)(CategorySearch);
And the data structure is
[ {value: "f1fffsf", label: "Soccer (aaa)"},
{value: "we1qwee", label: "bbb"},
{value: "fewer1", label: "ccc"},
{value: "sdfwer11", label: "ddd"}]
is like this. My console.log statements show that ‘convert’ has a correct value, however, the setOptions(convert) returns ‘[ ]’ just this empty array.
I tried setOptions(8392) and it does update it to 8392. What have I done wrong here?