简体   繁体   中英

React JS: Uncaught TypeError: getState is not a function

I'm trying to create a simple API call to the server. To make it I have created a file named - likes.js , inside it I have:

import axios from 'axios';
import tokenConfig from './auth';

// Like Report
export const likePostas = (report_public_id) => (dispatch, getState) => {
  console.log('Trying to call the server')
  axios
    .post(`/api/report/like?report=${report_public_id}`, tokenConfig(getState))
    .then((res) => {
      console.log(res.data)
    })
    .catch(err => {
      console.log(err.response.data)
    });
};

So basically it should be working, the other thing is that I need to pass in the token to the headers, so I have another file for that which is auth.js

// Setup config with token - helper function
export const tokenConfig = (getState) => {
  // Get token from state
  const token = getState().auth.token;

  // Headers
  const config = {
    headers: {
      'Content-Type': 'application/json',
    },
  };

  // If token, add to headers config
  if (token) {
    config.headers['Authorization'] = `Token ${token}`;
  }

  return config;
};

export default tokenConfig;

Now I need to just call it by pressing a button inside JSX. Here's my code:

import React, { useEffect, useState } from "react";
import { Button } from "../ButtonElement";
import { likePostas } from "../actions/likes";


const ReportCards = ({ report }) => {
  const IsVerifiedDiv = (
    <IsVerified>
      <GoVerified />
      <IsVerifiedToolTip>
        This user is <span style={{ color: "#01BF71" }}>Verified</span>
      </IsVerifiedToolTip>
    </IsVerified>
  );

  useEffect(() => {
    // Update the document title using the browser API
    document.title = `Winteka - View Report`;
    window.scroll({
      top: 0,
      left: 0,
      behavior: "smooth",
    });
  }, [0]);

  return (
    <>
        <BtnWrap2 onClick={likePostas(report.public_id)} />
    </>
  );
};

export default ReportCards;

But as I press the button I get this error:

react-dom.development.js:327 Uncaught TypeError: getState is not a function

It seems that you are using react-redux and redux-thunk and likePostas is an async action creator.

Instead of calling likePostas action creator yourself, you need to let react-redux call it with the values for the two parameters that it takes, ie dispatch and getState . Currently the problem is that as you are calling likePostas action creator yourself, dispatch and getState are undefined because you never pass those arguments to the function returned by likePostas .

Solution

Add an onClick listener on BtnWrap2 that will dispatch likePostas action creator.

Import the useDispatch hook from the react-redux package.

import { useDispatch } from "react-redux";

then use this useDispatch hook to dispatch the likePostas action when the button is clicked.

const dispatch = useDispatch();

const handleClick = (id) => {
   dispatch(likePostas(id));
}; 

and add this handleClick an a click listener on the BtnWrap2 component.

<BtnWrap2 onClick={() => handleClick(report.public_id)} />

I suggest that you visit the following links to learn how to use react-redux and redux-thunk :

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM