B
B
Bogdan2020-07-10 10:34:55
React
Bogdan, 2020-07-10 10:34:55

React Redux why is component not updating after asynchronous store update?

I make a set from a reducer into a state from local json

let initialState = {};

fetch('./data.json')
  .then((response) => response.json())
  .then((json) => Object.assign(initialState, json));

export default function data(state = initialState) {
  return state;
}


I get the state in the component, but the component is not updated according to the data that is in the state
import React from 'react';
import { useSelector } from 'react-redux';

export default (prop) => {
  const count = useSelector((state) => state);
  console.log(count);
  console.log(count.data);
  console.log(count.data.button);
  return (
    <button type="button" className={`button${(prop.bg ? ' button_bg' : '')}`}>
      {count.data.button ? count.data.button : '000000000'}
    </button>
  );
};


This is how the console.log looks like in the console from the code above

5f08191ea35c3050184882.png

How to force the component to take values ​​from the store or what am I doing wrong ?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
Loli E1ON, 2020-07-10
@Khokhycg

You need to use redux-thunk here. Or make a request in the component and dispatch the action with the incoming data.
You can only change the state with pure functions, and you also need to adhere to the immutability of the data.

B
Bogdan, 2020-07-10
@Khokhycg

As mentioned above, you need to use redux-thunk. Here is a good article on the subject

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question