Home > database >  How to declare useState conditonally?
How to declare useState conditonally?

Time:11-12

For my problem , right now I am getting data from api like this.

const fetchSomething = () => dispatch => {
    return axios
        .get('productsapi/getsomething', {
        })
        .then(res => {
            dispatch({
                type: FETCH_SOMETHING,
                payload: res.data[0].Groups[0].Products,
                payGroup: res.data[0],
            });
        })
        .catch(err => {
            console.log('fetching error');
            throw err;
        });
};

As you can see I am getting 2 kind of data from an api payload and paygroup because of the problem I encountering in the component.

Here is the component

let hotProductList = useSelector(state => state.productReducer.hotProduct);
let hotProductGroup = useSelector(
        state => state.productReducer.newHotProductGroups,
);

const [homeHotProductList, setHomeHotProductList] = useState(hotProductGroup.Groups[0].Products);

//No Error
//---------
//const [homeHotProductList, setHomeHotProductList] = useState(hotProductList); 
//---------

As you can see in the useState. If I want to render the initial productList using data from payGroup I have to declare like useState(hotProductGroup.Groups[0].Products) . The problem is that, this kind of declaring always return error which state that

undefined is not an object

But If I want to render the initial productList using data from payload this error does not occur.

What Should I do to make the declaration works for the payGroup without getting error

CodePudding user response:

I assume homeHotProductList is an array. You can set your homeHotProductList in useEffect. Add hotProductList and hotProductGroup as dependency to useEffect. So whenever these value changes you can set homeHotProductList using setHomeHotProductList inside useEffect conditionally.

let hotProductList = useSelector(state => state.productReducer.hotProduct);
let hotProductGroup = useSelector(
        state => state.productReducer.newHotProductGroups,
);

const [homeHotProductList, setHomeHotProductList] = useState([]);


useEffect(() => {
 // here you can set homeHotProductList conditionally

}, [hotProductList, hotProductGroup])

And regarding this error

undefined is not an object

You can use Optional chaining or Nullish coalescing operator if you're not getting value like hotProductGroup?.Groups?.[0]?.Products ?? []

  • Related