leabum
leabum

Reputation: 395

React: How to return value from method of Context

I want to return a boolean value from a method within my Context, how would I do that? My approach is obviously not correct. As a beginner I often get confused which syntax to use where.

This is my ContextProvider:

import React, { Component } from 'react';
import AuthContext from './AuthContext';

// Then create a provider Component to update children Components once the user role changes
class AuthProvider extends Component {
    constructor() {
      super()
      this.state = {
          role: "none" //roles: none, admin, kursleiter
      }
  }

  render() {
    return (
      <AuthContext.Provider value={{
        state: this.state,
        isAuthenticated: () => {
          if (this.state.role == "kursleiter" || this.state.role == "admin") {
            return true
          }
          return false},
        setRole: (newRole) => this.setState({
            role: newRole
        })
      }}>
        {this.props.children}
      </AuthContext.Provider>
    )
  }
}

export default AuthProvider

And this is where I want to use my boolean (see the if-Statement):

import React from "react";
import { Route, Redirect } from "react-router-dom";
import AuthContext from '../../AuthContext';

export const ProtectedRoute = ({ component: Component, ...rest }) => {
    return (
    <Route
      {...rest}
      render={props => {
        if (
            <AuthContext.Consumer>
                {(context) => (
                  <React.Fragment>
                    { context.isAuthenticated() == true ? true : null}
                  </React.Fragment>
                )}
            </AuthContext.Consumer>
        ) {
          return <Component {...props} />;
        } else {
          return (
            <Redirect
              to={{
                pathname: "/",
                state: {
                  from: props.location
                }
              }}
            />
          );
        }
      }}
    />
  );
};

Upvotes: 1

Views: 1737

Answers (1)

Hamza El Aoutar
Hamza El Aoutar

Reputation: 5657

One way to do this would be to use useContext hook, which lets you read the context and subscribe to its changes.

In this case you are interested in extracting the function isAuthenticated from the context and using it inside the render prop of Route:

export const ProtectedRoute = ({ component: Component, ...rest }) => {
  const { isAuthenticated } = useContext(AuthContext);

  return (
    <Route
      {...rest}
      render={(props) =>
        isAuthenticated() ? (
          <Component {...props} />
        ) : (
          <Redirect
            to={{
              pathname: "/",
              state: {
                from: props.location,
              },
            }}
          />
        )
      }
    />
  );
};

Upvotes: 1

Related Questions