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

Problem with <meta> tag occurring when initial-scale is adjusted

Initially, in the index.html file: <meta name="viewport" content="width=device-width, initial-scale=1" /> I decided to modify it to: <meta name="viewport" content="width=device-width, initial-scale=2" /> ...

Dynamic refresh of content with Ajax

Recently, I stumbled upon the platform Polyvore and decided to test it out. While experimenting with its "Create a set" feature, I noticed that the site provides a view of items either from your own collection or sourced elsewhere. An interesting observat ...

Best practice for passing a variable argument in a JavaScript callback?

After searching the internet without success, I couldn't find the answer to my problem. The issue revolves around a function that I have: function ParentFunction (DataBase, Parameters) { for (k = 0; k < DataBase.length; k++){ var ...

Is there a way to preserve all the downloaded node modules in the package.json file?

Is there a way to keep track of all the node modules installed in package.json without the need for reinstalling them? I've heard about running npm init --yes, but I'm not entirely convinced if that will do the trick. Any assistance on this mat ...

Replicate the preceding input data by simply clicking a button

Here is some HTML and jQuery code that I am working with: $(".btn-copy").click(function() { var previousContent = $(this).prev()[0]; previousContent.select(); document.execCommand('copy'); }); <script src="https://cdnjs.cloudflare.com ...

Error with XMLHTTPRequest loading in beforeunload/unload event handlers in iOS 13.4.1 encountered

Currently, I am utilizing XMLHTTPRequest for data posting in JavaScript. Previously, it functioned smoothly on Safari and Chrome browsers up to iOS 13.3.1. However, upon updating to the latest OS version, iOS 13.4.1, an error message stating "XMLHTTPReques ...

import component dynamically from object in Next.js

Currently, I have a collection of components that I am aiming to dynamically import using next/dynamic. I'm curious if this is achievable. Here's the object in interest: // IconComponents.tsx import { Tick, Star } from 'components ...

Effortlessly handle form submission with jQuery AJAX, automatically redirecting upon successful

I am working on a project using ASP.Net MVC where I have a view that submits form data to a controller action. In order to make this form submission more dynamic, I am trying to utilize jQuery to post the form via an AJAX call with the following code: $(" ...

My custom class is being ignored by Tailwind CSS within breakpoints

I'm attempting to incorporate some animation on the height property within the md breakpoint, but for some reason Tailwind CSS isn't applying my class. <div className={`h-12 bg-blue flex w-full text-white fixed mt-1 md:bg-white ${scrolling ? ...

Balancing asynchronous tasks - masteringlearnode - program that initially succeeded but eventually faltered

node version: v4.4.3 npm version: 3.8.9 Error output Your entered data does not match the expected values. ──────────────────────────────────────────────── ...

What is the reason behind the necessity of using setTimeout with a delay of at least 50ms for JS .focus()

Problem While creating a page for a client at work, I encountered an issue with a slide-out search bar. When clicking the button to open the search input field (which starts off hidden), I want the focus to shift to that input field. Oddly, I found that ...

MUI Input component does not support the use of the oninput attribute

My MUI Input component is defined like this, but the oninput attribute doesn't seem to work in MUI: <Input variant="standard" size="small" type="number" inputProps={{ min: '0', o ...

Access various results from a jQuery function

Is there a way to efficiently extract the values of petKeys and employeeKey using the jQuery functions provided below? var whenSelectDateFromCalendar = function () { initKeyValues(); petKeys = ? employeeKey = ? }; var initKeyValues = function ...

Discovering the power of ng-change in an Angular typeahead search functionality

I am facing an issue with displaying the result list when searching for users on key press using customTemplate.js. The list is not showing up after the first key press. Below is the code I am using: <input type="text" placeholder="Search people here ...

What is the process of transferring information to a property in JSON within a Jade (Pug) file?

Initially, I transmit data to a Jade template using Node.js. app.get('/', function(req, res){ var arr = new Array( {firstname: 'Gil-dong', lastname: 'Hong'}, {firstname: 'Yeong-sil', lastname: &a ...

Navigating between components in React: How to create links that open a different component on the same page

I need help with a basic app that consists of a login page and a registration page. I want to add links between these pages using React. I would appreciate input from experienced colleagues on the best approach to achieve this. Below is the code for the lo ...

Pressing the button in JqGrid will assign an identification number

I am facing an issue with selecting rows in my JqGrid, so I found a solution on which suggests that I need an ID for every row. Whenever I add data to my Grid by pressing a button, I tried assigning each row an ID using a simple click counter function. H ...

Is there a way to utilize JavaScript in order to trigger a CSS animation to occur at a designated time during a video

I have a cool animated image element that I want to play at a specific point in time during a video using JavaScript. I'm not sure how to make it happen, but I know the .currentTime property could be the key. My goal is for the animation to only play ...

Creating a JSON Response Using PHP API

I created a basic JSON response to test the functionality of an AJAX request on a mobile device. Using a local domain called test.local, I generated a json response. header("Content-Type:application/json; charset=utf-8"); echo json_encode(array('nam ...

Encountering an error while updating data with react-hook-form

Struggling to configure a react-hook-form for create and update operations using material ui autocomplete and textfield. The issue arises with a field that has autocomplete functionality. When passing an input value, it displays correctly, but upon form s ...