Using withRouter with context react api

Using withRouter with context react api
0

#1

hello,

so i am working on a personal project and chose to use the context api in react for state management since the app is simple. the problem i have tho is that i need to use to withRouter on in my user-context.js file, to access the history do that i can redirect to the login page if the user in not logged in, this is my user-context file:

import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'

const UserContext = React.createContext();


class Provider extends Component{
    state = {
        user:{
            username: ''
        }
    }

    componentDidMount(){
        //talk to the server to see if the client is authorized.
        fetch('http://localhost:8080/', {
         headers: {
           authorization: "Bearer "+ localStorage.token
         }
        })
        .then(res => res.json())
        .then(result => {
          if(result.user){
            this.setState({
              user: {
                ...result.user
              }
            })
          }else{
              //if not delete the old token and redirect to login page
            localStorage.removeItem('token');
            this.props.history.push('/login');//this is not available
          }
          
        })
        .catch(err => console.log(err));
    }

    render(){
        return (
            <UserContext.Provider value={{state: this.state}}>
                {this.props.children}
            </UserContext.Provider>
        )
    }
}


export { 
    withRouter(Provider),//this is where i have a problem
    UserContext }

would really appreciate any help. and if you need any additional info just ask.
thank you


#2

fixed it by separating the UserContext and Provider in two files so i can export default the provider with withRouter export default withRouter(Provider).

apparently you can not use the withRouter when only using export .