Sylvain Attoumani
Sylvain Attoumani

Reputation: 1194

react context with fetched data

I'm working with react and NextJS. What i want is to send the data about my user to all my pages and to do so I'm using context. the thing is, I got my user data from an api and it doesn't seems like I got the updated data in my pages. This is my app.js :

...
import Header from '../component/header'
export default class MyApp extends App {
    state = {
        username: null
    };
    componentDidMount() {
        fetch('API-URL', details_no_care)
            .then(response => response.json())
            .then(data => this.setState({username : data}));
    }
    render() {
        const {Component, pageProps} = this.props;
        return (
            <React.Fragment>
                <Head>
                    <title>My title</title>
                </Head>
                <UserContext.Provider value={{username : this.state.username}}>
                        <Header/>
                        <Component {...pageProps} />
                </UserContext.Provider>
            </React.Fragment>
        );
    }

}

And this is my UserContext :

import React from "react";
export const UserContext = React.createContext(
);

And my header.js :

class header extends React.Component {
    constructor(props, context) {
        super(props,context);
        this.state = {
            username: context.username
        }
    }
    render () {
        return ( 
            <React.Fragment>
                 {this.state.username}
            </React.Fragment>
        )
    }
}


But it's never displaying anything.

I'm 100% sure that the data can come from the app to the header. Because If I initialise username in app.js with "toto" it will display "toto".

Also if I console.log(this.context.username) in componentDidUpdate I do have the right data. But react won't let me do a this.setState in the componentDidUpdate

Upvotes: 2

Views: 687

Answers (2)

ChandraKumar
ChandraKumar

Reputation: 547

This is a legacy approach... However, it's not yet deprecated!

You are missing to state contextType in the consumer(Header component)

class Header extends Component {
  static contextType = UserContext;// you are missing this one
  constructor(props, context) {
    super(props, context);
    this.state = {
      username: context.username
    };
  }
  render() {
    console.log(this.state.username);
    return <React.Fragment>{this.state.username}</React.Fragment>;
  }
}

Upvotes: 0

Sylvain Attoumani
Sylvain Attoumani

Reputation: 1194

So I found the solution. I'm not using the state. Just everywhere I'm using this.state.user I replaced it with this.context.user. Looks like it's working. Don't hesitate to tell me if that's a bad practice or anything!

Upvotes: 1

Related Questions