Home > database >  Setting the default state after fetching the product returns undefined in ReactJS
Setting the default state after fetching the product returns undefined in ReactJS

Time:12-13

I am trying to set default states for color, size, etc. when I dispatch the getProduct(id) action, I get the product and everything is fine (my product has a size in it: size: ['s','m'...]). I want it to be the first element in the array by default, i do something like this:

  const { id } = useParams();
  const dispatch = useDispatch();

  const { product, isLoading } = useSelector(state => state.product);

  useEffect(() => {
    dispatch(getProduct(id));
  }, [dispatch, id]);


  const [sizeState, setSizeState] = useState(
    product?.size?.length > 0 && product?.size[0]
  );

console.log(product?.size?.length > 0 returns false console.log(product?.size[0]) returns undefined.

This is my product object: Product object

CodePudding user response:

Just add useEffect observer for product state. and then use unshift method of array

useEffect(()=>{

if(product){


setSize((prevState)=>[product?.size,...prevState])
}

},[product])

CodePudding user response:

To me it looks like you didn't parse the JSON object after fetching the product. Make sure to parse it after fetching.

fetch(URL, OPTIONS).then(res => res.json());
  • Related