owdji
owdji

Reputation: 371

Redux State changes but component not rerendering

My issue is that my redux state is updating (I can see it in the redux dev tool) but my component is not updating, it's not putting the last value of my array initialState.userWeight Here is what my reducer looks like :

case 'NEWWEIGHT':
           const weight = action.payload.weight
           const date = action.payload.date
           state.userWeight = [...state.userWeight, {weight: weight, date: date}]
           return {...state}

Here is my initialState :

const initialState = {
    userName: '',
    userSize: 0,
    userWeight: [],
    userDate: '',
}

Here is what my component looks like :

    const userWeightRedux = useSelector(state => state.userInfo.userWeight[Array.length - 1].weight)

    console.log(userWeightRedux)

...
<Text style={styles.user}>{userWeightRedux}</Text>

So console.log(userWeightRedux) dosen't change. I am new to react, redux and don't fully understand the spread syntax, maybe the problem is here but did'nt find anything, hope you can help me :).

Upvotes: 1

Views: 958

Answers (2)

spender
spender

Reputation: 120518

Although other answers better address your specific problem...

You're mutating your state. Although you're returning a new state object, you're leaving your old state in a mess. This will cause subtle problems. Don't mutate anything in a reducer. So...

// this line mutates the "outgoing" state
state.userWeight = [...state.userWeight, {weight: weight, date: date}]
return {...state}

should be rewritten as:

return {...state, userWeight: [...state.userWeight, {weight: weight, date: date}]} 

Upvotes: 1

Nicola Scionti
Nicola Scionti

Reputation: 546

Array.length is a prototype property of Arrays. You can't use it that way. By default is always 1. So you are retrieving always the first element of state.userInfo.userWeight. Use instead:

const userWeightRedux = useSelector(state => state.userInfo.userWeight[state.userInfo.userWeight.length - 1].weight)

or a more gentle sintax:

const userWeightRedux = useSelector(state => state.userInfo.userWeight.slice(-1)[0].weight)

Upvotes: 2

Related Questions