user3378165
user3378165

Reputation: 6896

Component gets rendered before getting its values

I have an AuthContext file for the user info. when I console.log the data returning from the api, the user is being set properly. However the AuthContext component gets rendered before the api returns the user's value so on the page that uses the context the user properties are always null.

Any idea on how to solve that?

AuthContext:

const AuthContext = React.createContext();

class AuthProvider extends React.Component {
  state = {
    user: {
      name: '',
      isAdmin: false,
    },
  };

  componentDidMount = async () => {
    try {
      const { data: user } = await axios.get('/api/user/GetUser');
      this.setState(user);
    } catch (error) {}
  };

  render() {
    const { user } = this.state;
    return <AuthContext.Provider value={{ user }}>{this.props.children}</AuthContext.Provider>;
  }
}

const AuthConsumer = AuthContext.Consumer;

export { AuthProvider, AuthConsumer };

Hedrer component that call the AuthContext:

import { AuthConsumer } from '../AuthContext';
import Welcome from './Welcome';
import Initial from './Initial';
export default ({ user, children }) => (
  <AuthConsumer>
    {({ user }) => (
      <div css={headerStyles}>
        <div>
          <Welcome name={user.name} />
          <Initial name={user.name} />
        </div>
        {children}
      </div>
    )}
  </AuthConsumer>
);

Upvotes: 0

Views: 72

Answers (1)

nbokmans
nbokmans

Reputation: 5747

I think you accidentally forgot to add the curly brackets to update your state, you are doing

this.setState(user);

You need to wrap your the arguments to your setState call in curly brackets like so:

this.setState({ user });

Any changes to the state will trigger React to re-render. More information on setState can be found here: https://reactjs.org/docs/react-component.html#setstate

Upvotes: 1

Related Questions