admin管理员组文章数量:1404927
I'm new to React and trying to build an app with a cart feature where users can add robots to the cart. I'm using Context API
to provide cart across the app and useReducer
for states. The robots are being fetched from a server and load just fine. But I can't seem to find a way to set the initial state of the reducer
using fetched products. The state always returns an empty array for robots. How to solve this?
const CartProvider = ({ children }) => {
const [robots, setRobots] = useState([]);
useEffect(() => {
fetch('http://localhost:8000/api/robots')
.then(res => res.json())
.then(data => setRobots(data?.data))
}, [])
const initialState = {
robots: [...robots],
cart: []
}
const [state, dispatch] = useReducer(cartReducer, initialState);
return (
<CartContext.Provider value={{ state, dispatch }}>
{children}
</CartContext.Provider>
);
}
export default CartProvider;
I'm new to React and trying to build an app with a cart feature where users can add robots to the cart. I'm using Context API
to provide cart across the app and useReducer
for states. The robots are being fetched from a server and load just fine. But I can't seem to find a way to set the initial state of the reducer
using fetched products. The state always returns an empty array for robots. How to solve this?
const CartProvider = ({ children }) => {
const [robots, setRobots] = useState([]);
useEffect(() => {
fetch('http://localhost:8000/api/robots')
.then(res => res.json())
.then(data => setRobots(data?.data))
}, [])
const initialState = {
robots: [...robots],
cart: []
}
const [state, dispatch] = useReducer(cartReducer, initialState);
return (
<CartContext.Provider value={{ state, dispatch }}>
{children}
</CartContext.Provider>
);
}
export default CartProvider;
Share
Improve this question
asked Dec 13, 2021 at 9:49
TajminTajmin
4031 gold badge8 silver badges23 bronze badges
1
-
1
Since the initial state value is fetched asynchronously you'll need to dispatch an action to set the
state
value. Can you share yourcartReducer
function and any related code like actions and action creators? – Drew Reese Commented Dec 13, 2021 at 9:55
2 Answers
Reset to default 3Since the initial state value is fetched asynchronously you'll need to dispatch an action to set the state
value.
Example:
const cartReducer = (state, action) => {
switch(action.type) {
... other reducer cases ...
case 'INITIALIZE_CART':
return action.payload;
default:
return state;
}
};
CartProvider
const initialState = {
robots: [],
cart: []
};
const CartProvider = ({ children }) => {
const [robots, setRobots] = useState([]);
const [state, dispatch] = useReducer(cartReducer, initialState);
useEffect(() => {
fetch('http://localhost:8000/api/robots')
.then(res => res.json())
.then(data => {
dispatch({
type: 'INITIALIZE_CART',
payload: {
...initialState,
robots: data?.data,
}
});
});
}, []);
return (
<CartContext.Provider value={{ state, dispatch }}>
{children}
</CartContext.Provider>
);
};
It's mon to also hold some state on the app initialization status. UI conditionally renders based on this state value.
Example:
const initialState = {
initialized: false,
robots: [],
cart: []
};
...
const cartReducer = (state, action) => {
switch(action.type) {
... other reducer cases ...
case 'INITIALIZE_CART':
return {
...action.payload,
initialized: true,
};
default:
return state;
}
};
const [state, dispatch] = useReducer(cartReducer, initialState);
useReducer
will not monitor changes to initialState
, it will only consider its initial value. You can just dispatch an action to update the state once the data is fetched.
const initialState = {
robots: [],
cart: []
}
const CartProvider = ({ children }) => {
const [state, dispatch] = useReducer(cartReducer, initialState);
useEffect(() => {
fetch('http://localhost:8000/api/robots')
.then(res => res.json())
.then(data => {
// dispatch action to update the reducer state
})
}, [])
return (
<CartContext.Provider value={{ state, dispatch }}>
{children}
</CartContext.Provider>
);
}
export default CartProvider;
If the nested ponents don't work well until the state is populated then you can conditionally render children
:
return (<CartContext.Provider value={{ state, dispatch }}>
{state?.robots?.length > 0 && children}
</CartContext.Provider>);
本文标签: javascriptHow to set useReducer initial state using API responseStack Overflow
版权声明:本文标题:javascript - How to set useReducer initial state using API response? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744870901a2629623.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论