how to change from useState to useReducer

71 views Asked by At

The following code I am trying to convert it to useReducer but few things I am not able to figure it out. In the following code, handleClick updates the state and calls other functions for further actions. In useReducer, I can update the state but how to call other functions.

 const handleClick = (id) =>{
    let matchedEl = userArray.find(el => el.pic == picArray[id].pic)
    if(matchedEl){
        alert('game over')`
        setUserArray([]);
        gameOver();
    } else {
        let picObj = { "pic": picArray[id].pic}
        setUserArray([...userArray, picObj]) //updates the state
        if(userArray.length == 12){
            setUserArray([])
            scoreFn();
            return;
        }
        let shuffledArray = shufflePicArray();
        setPicArray([...shuffledArray]) //updates the state
        scoreFn();
    }   
}

return (
        <Container >
                        <Card onClick={() => handleClick(id)} /> </Card>
            </Row>             
        </Container>)}
  

With useReducer

const initialState = {
    picArray: pics,
    userArray: []
}
function reducer(state, action){
    switch(action.type){
        case "handleClick" :
        {
            let id = action.payload;
            const shuffledArray = state.picArray.sort( () => Math.random() - 0.5)
            let matchedEl = state.userArray.find(el => el.pic == state.picArray[id].pic)
            console.log(matchedEl)
            let picObj;
            if(!matchedEl){
                    picObj = { "pic": state.picArray[id].pic}
                } else {
                    alert('game over')
                    gameOver(); //can't call the function is not defined yet
                }
        return{
            state,
           picArray:[...shuffledArray], //this works
           userArray:[...state.userArray, picObj] //this works
        }
    }
    default:
      return state;
    }
}

const Newmain = ({scoreFn, gameOver}) => {
    const [state, dispatch] = useReducer(reducer, initialState)

return(
<card onClick={() =>dispatch({type:'handleClick', payload:id})} />
)}```


The useState handleClick function does a lot more things and how to reproduce while using useReducer. 
1

There are 1 answers

0
M.Abdeldayem On BEST ANSWER

to answer your question, you can add

const handleClick = (id) => {
//do stuff here
dispatch({type:'handleClick', payload:id})
}


and then <card onClick={() => handleClick(id)} /> as it was, but i would recommend to use useCallback depending on your use case