I am trying get the fetched array from the zustand store, but it's returned as empty.
script.jsx
const store = Zstore();
const params = useParams();
useEffect(() => {
store.fetchStock(params.id);
}, []);
console.log(store.stock); // Empty array
Zstore.js
import { create } from 'zustand';
import axios from 'axios';
const Zstore = create((set) => ({
stock: [],
fetchStock: async (id) => {
const res = await axios.get('http://127.0.0.1:8000/searchList/')
const stock = res.data.filter((stock) => stock.symbol == id.toUpperCase()).map((stock) => {
return {
symbol: stock.symbol,
name: stock.name,
}
});
set({stock});
console.log(stock); // Array not empty
},
}));
export default Zstore;
I did attempt to add store.stock.length
as a dependency to the useEffect
but to no avail.
Seems like your component is not rerendering due to state changes,
try to update your component this way,
Your store selection should look like this const stock = Zstore(state => state.stock);
const params = useParams();
const stock = Zstore(state => state.stock);
useEffect(() => {
Zstore.getState().fetchStock(params.id);
}, [params.id]);
// This will re-render the component when `stock` changes, displaying the updated data.
console.log(stock);