The error message "Encountered an issue when trying to access properties of undefined (reading 'getState')" was

Currently working on developing an app that utilizes a Django backend and React frontend. The goal is to enable users to log in, receive refresh and access tokens from Django, store the token in local storage, and redirect authenticated users to a static profile page.

Encountering some console errors:

Uncaught TypeError: Cannot read properties of undefined (reading 'getState')
    at Provider.js:20:1
    at mountMemo (react-dom.development.js:15442:1)
The above error occurred in the <Provider> component:
    in Provider (at src/index.js:21)
    in Router (at src/index.js:20)

Consider incorporating an error boundary for customized error handling.

Below is my login.js code snippet:

const Login = () => {
    const [username, setUserName] = useState('');
    const [password, setPassword] = useState('');

    const handleSubmit = e => {
        e.preventDefault()
        try {
            const response = AxiosInstance.post('/api/token/',{
                username: username,
                password: password
                });
                console.log('from api/token we get this:')
                console.log(response)
                AxiosInstance.defaults.headers['Authorization'] = "JWT " + response.access;
                localStorage.setItem('access_token', response.access);
                localStorage.setItem('refresh_token', response.refresh);
                console.log('JWT response.access to refresh: ')
                return response;
        } catch (error) {
            throw error;
        }
    } 

Login.propTypes = {
    login: PropTypes.func.isRequired,
    auth: PropTypes.object.isRequired
};

const mapStateToProps = state => ({
    auth: state.auth
});

export default connect(mapStateToProps, {
    login
}) (withRouter(Login));
//export default Login;

LoginActions.js excerpt:

export const login = (userData, redirectTo) => dispatch => {
  axios
    .post("/api/token/", userData)
    .then(response => {
      const { auth_token } = response.data;
      setAxiosAuthToken(auth_token);
      dispatch(setToken(auth_token));
      dispatch(getCurrentUser(redirectTo));
    })
    .catch(error => {
      dispatch(unsetCurrentUser());
      toastOnError(error);
    });
};

export const getCurrentUser = redirectTo => dispatch => {
  axios
    .get("/users/")
    .then(response => {
      const user = {
        username: response.data.username,
        email: response.data.email
      };
      dispatch(setCurrentUser(user, redirectTo));
    })
    .catch(error => {
      dispatch(unsetCurrentUser());
      toastOnError(error);
    });
};

export const setCurrentUser = (user, redirectTo) => dispatch => {
  localStorage.setItem("user", JSON.stringify(user));
  dispatch({
    type: SET_CURRENT_USER,
    payload: user
  });

  console.log("set user" + redirectTo);
  if (redirectTo !== "") {
    dispatch(push(redirectTo));
  }
};

Reducer.js details:

const createRootReducer = history =>
    combineReducers({
        router: connectRouter(history),
        createUser: signupReducer,
        auth: loginReducer
    });
export default createRootReducer;

My Root.js implementation:

export default ({ children, initialState = {} }) => {
  const history = createBrowserHistory();
  const middleware = [thunk, routerMiddleware(history)];

  const store = createStore(
    rootReducer(history),
    initialState,
    applyMiddleware(...middleware)
  );

  // check localStorage
  if (!isEmpty(localStorage.getItem("token"))) {
    store.dispatch(setToken(localStorage.getItem("token")));
  }
  if (!isEmpty(localStorage.getItem("user"))) {
    const user = JSON.parse(localStorage.getItem("user"));
    store.dispatch(setCurrentUser(user, ""));
  }

  return (
    <Provider store={store}>
      <ConnectedRouter history={history}>{children}</ConnectedRouter>
    </Provider>
  );
};

Utils.js content:

export const setAxiosAuthToken = token => {
  if (typeof token !== "undefined" && token) {
    // Apply for every request
    axios.defaults.headers.common["Authorization"] = "Token " + token;
  } else {
    // Delete auth header
    delete axios.defaults.headers.common["Authorization"];
  }
};

export const toastOnError = error => {
  if (error.response) {
    // known error
    toast.error(JSON.stringify(error.response.data));
  } else if (error.message) {
    toast.error(JSON.stringify(error.message));
  } else {
    toast.error(JSON.stringify(error));
  }
};

export const isEmpty = value =>
  value === undefined ||
  value === null ||
  (typeof value === "object" && Object.keys(value).length === 0) ||
  (typeof value === "string" && value.trim().length === 0);

Finally, index.js file:

const history = createBrowserHistory();

ReactDOM.render(
  <Router history={history}>
    <Provider>
        <App />
    </Provider>
  </Router>,
  document.getElementById('root')
);

serviceWorker.unregister();

Looking for suggestions or advice on troubleshooting the issues I'm facing!

Answer №1

Failure to provide the store to the Provider:

ReactDOM.render(
  <Router history={history}>
    // Ensure the correct import of store
    <Provider store={store} >
        <App />
    </Provider>
  </Router>,
  document.getElementById('root')

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Update the display immediately upon a change in the state

In my app.js file, the code looks like this: export const App = () => { const [selectedMeals, setSelectedMeals] = useState<string[]>(["allItems"]); const onCheckHandler = (e: any) => { const checkedValue = e.target.value; if (e.targ ...

I'm looking for a solution to reorganize my current state in order to display the image URL

My React component, which also utilizes TypeScript, is responsible for returning a photo to its parent component: import React, { useEffect, useState } from "react"; import axios from "axios"; export const Photo = () => { const [i ...

Utilizing jQuery to dynamically update background colors within an ASP repeater based on the selected value of a dropdown list

On my asp.net web page, I have a repeater that displays a table with various fields in each row. I am trying to make it so that when the value of a dropdown within a repeater row changes, the entire row is highlighted in color. While I have achieved this s ...

React - Obtain User Login Details and Verify

I am working on a React project that includes a Login Form. The code has been organized into small components for reusability, but I am unsure of how to retrieve and validate user credentials (username and password). Is there a method available to validate ...

React useEffect alert: Exceeding maximum update depth limit. Any solutions to bypass this issue?

In the code snippet below, I am utilizing the useEffect hook to monitor changes to a percentage variable and then initiating a timer to increment that variable every second. This process starts as soon as the page loads. The percentage variable is crucial ...

Having difficulty with express.index when trying to send a JSON object

Express is my tool of choice for creating a simple web page. The code in my index.js file looks like this: exports.index = function(req, res){ res.render( 'index', { title: 'Expressssss', Tin: va ...

What are the steps for incorporating a YouTube playlist into a website?

I'm in the process of creating a website and I'd like to incorporate a YouTube video playlist that looks similar to this example - http://www.youtube.com/user/icicibank/home. I plan to use HTML5, JavaScript, and the YouTube API. Can you provide g ...

Is there a way to make the header reach the full width of the page?

Is there a way to make my header extend across the entire page? I attempted using margin-left and right, but it didn't yield the desired outcome. Header.css .header{ background: green; height: 70px; width: 100%; display: flex; ju ...

What steps do I need to follow in order to successfully deploy a Next.js application with MongoDB to Heroku?

I've been facing challenges while attempting to deploy my Next.js application with mongoDb on the Heroku platform. The build process is successful without any errors, but unfortunately, my app does not function correctly. Upon checking the Heroku logs ...

What is the best way to differentiate between a JSON object and a Waterline model instance?

Note: I have posted an issue regarding this on the Waterline repo, but unfortunately, I have not received a simpler solution than my current workaround. Within my User model, along with default attributes such as createdDate and modifiedDate, I also have ...

Surprising 'T_ENCAPSED_AND_WHITESPACE' error caught me off guard

Error: An error was encountered while parsing the code: syntax error, unexpected character (T_ENCAPSED_AND_WHITESPACE), expected identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in C:\wamp\www\html\updatedtimel ...

Is it possible to create multiple text input components using the "each" function, and how can I update the state by combining all of them together?

I am looking to create a text-based word game where the length of each word changes with every level. Each letter will be placed in its own box, forming a matrix (e.g. 10 words, length: 10 => 10x10 matrix). How can I generate multiple text input componen ...

Is it possible to utilize href alongside the urlRouterProvider?

Within my angularjs application, I opted to switch from using ngRoute (routeProvider) to ui.router (urlRouterProvider) module and stateProvider for transitioning between different states in the app. However, I recently discovered that ui-router only suppo ...

To access the link, simply click once if there is no child menu. However, if there is a child menu attached, be sure to click

I am working on a mobile menu that is designed to slide out when clicked. Currently, the parent pages are displayed by default. I want to implement functionality where if a parent page has child pages, clicking on it will slide down the sub menu. If click ...

Exploring JSON objects in React for improved search functionality

Hey there! I'm working on implementing a search bar that updates the list of JSON entries based on user queries. Below is the code snippet that displays the video list (<Videos videos={this.state.data}/>). Initially, when the page loads, I have ...

Content within the Iframe is in the process of loading, followed by

Exploring the code below: <iframe id="myframe" src="..."></iframe> <script> document.getElementById('myframe').onload = function() { alert('myframe is loaded'); }; </script> Is it a possibility that the ifra ...

The custom styles in Material UI are not being properly applied to the component

Currently diving into the world of Material UI with react js. Struggling with custom styling as everything seems right logically, but styles refuse to apply. Attempting to tweak the style of a button in the Create.js component using import { makeStyles } ...

React Native: Image display issue

I'm facing a problem with displaying an image. I've followed all the steps correctly as per a tutorial, but for some reason, my image is not showing up while the author's images are displayed perfectly. What could be causing this issue? I ha ...

Performance Issues Arise with Rapid Clicking [jQuery]

Having trouble with a gallery script I created that includes thumbnails, a large image, and navigation arrows. When you rapidly click on thumbnails or arrows during the transition, it causes delays in the process. The more clicks you make, the more noticea ...

The Owl Carousel npm package is experiencing issues within a ReactJS environment

Currently, I am developing a reactjs application and utilizing the owl carousel npm module to display some data. In my codebase, there is a component dedicated solely to rendering the owl carousel. To achieve this functionality, I have installed the owl c ...