I have a React app that gets initialized as simple as:

let globalTodos = some_fetch_from_localstorage();

...

function changeGlobalTodos() {
  globalTodos = another_fetch_from_localstorage();
}

...

ReactDOM.render(<ReactApp todos={globalTodos} />, document.getElementById('app'));

Inside of the app I'm doing the following:

constructor(props) {
  super(props);
  this.state = {
    todos: []
  };
}

static getDerivedStateFromProps(nextProps, prevState) {
  if (nextProps.todos !== prevState.todos) {
    return { todos: nextProps.todos };
  } else return null;
}

componentDidUpdate(prevProps, prevState) {
  if (prevProps.todos !== this.props.todos) {
    this.setState({ todos: this.props.todos });
  }
}

The problem is that whenever I update globalTodos, the props on the React app don't get updated: it stays on the initial globalTodos's value.

I have tried playing with getDerivedStateFromProps is being called only on first setup of the props while componentDidUpdate never gets called :-/

What am I missing here?

1 Answers

0
user1327787 On

I can't leave a comment, so I'll just post this here. React won't re-render unless you're updating a state.

I'd make globalTodos a state and add onto it from there using setState, then you can pass that on as a prop to the child component in your case ReactApp. You don't need to change them as states in your child component.

Example:

class Parent extends Component {
    constructor(props) {
        super(props);
        this.state = {
            globalTodos: initialFetchedArray
        };
    }

    changeGlobalTodos() {
        let newTodos = fetchNewArray;
        this.setState({globalTodos: newTodos});
    }

    ReactDOM.render(<ReactApp todos={globalTodos} />, document.getElementById('app'));
}

//You just need your prop here, here you can do whatever you want to do with the array if it's display you can use map
class Child extends Component {
    render {
        return(
         {this.props.todos}
        )
    }
}

Really the main thing here is making your globalTodos a state, using setState to change that state, and just passing that state down as a prop.