vitor13almeida
vitor13almeida

Reputation: 139

React Context error on rendering

I created an app to learn ReactJS. Unfortunately, when I was trying to use context I got 1 error on rendering, but my app compiles well.

This is my code:

import React, {Component} from 'react';

const LoginContext = React.createContext(null);

const user = {
    isLoggedIn: true,
    username: 'test',
};

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isLoggedIn: false,
            user: user,
        };
    }

    render() {
        return (
            <LoginContext.Provider user={this.state.user}>
                 <Welcome/>
            </LoginContext.Provider>
        );
        }
    }

class Welcome extends Component {
    render() {
        return (
            <div>
                <WelcomeText/>
            </div>
        );
    }
}

class WelcomeText extends Component {
    render() {
        return (
            <LoginContext.Consumer>
                <div>
                    {(user) => (<p>{user.username}</p>)}
                </div>
            </LoginContext.Consumer>
        );
    }
}

export default App;

This is the error: updateContextConsumer http://localhost:3000/static/js/bundle.js:20927:23

  20924 | {
  20925 |   ReactCurrentOwner.current = workInProgress;
  20926 |   ReactDebugCurrentFiber.setCurrentPhase('render');
> 20927 |   newChildren = render(newValue);
        |                 ^  20928 |           ReactDebugCurrentFiber.setCurrentPhase(null);
  20929 | } // React DevTools reads this flag.
  20930 | 

Can you help me solve this?

Upvotes: 5

Views: 9124

Answers (2)

Simon Park
Simon Park

Reputation: 91

I am currently working on React-16.8.6 and having an interesting bug. I'm not sure if it's the known issue or not but I am having the same error whenever I have a space between two characters '}' and '<' as you can see it line-30.

After (1) removing the space or (2) completely making a new line with , it was resolved.

Even though I love React a lot, it's not perfect and we can make it better together.

When having a space

After removing the space

Upvotes: 2

Shubham Khatri
Shubham Khatri

Reputation: 281686

ContextProvider needs a prop called value and not user

  <LoginContext.Provider value={this.state.user}>
        <Welcome/>
  </LoginContext.Provider>

Also the Context consumer has the children as a function and not the div

class WelcomeText extends Component {
    render() {
        return (
            <LoginContext.Consumer>
                  {(user) => (<div><p>{user.username}</p></div>)}
            </LoginContext.Consumer>
        );
    }
}

Upvotes: 4

Related Questions