简体   繁体   中英

UseState - Invalid hook call. Hooks can only be called inside the body of a function component

  • I am using useState to update response from API.

  • Then I am taking the data I need, and map them in a new array (arr)

  • After the above step I am updating the "setData" useState hook to use "data" state

  • But it is giving me Error "Invalid hook call. Hooks can only be called inside the body of a function component "

Here is the part of the code i am facing problem with

import {useEffect, useState} from 'react'
import logo from './logo.svg';
import './App.css';
import axios from 'axios'
import ReactSearchBox from 'react-search-box'
import { set } from 'express/lib/application';

function App() {

 
  let [data, setData] = useState()
  
  useEffect(onMount,[])

  function onMount(){
      
      axios.get('https://restcountries.com/v3.1/all').then(res=>{
        
        let arr = res.data.map((c)=>{
          return {key:c.name.common, value: c.name.common}
        })
        setData(arr)   
      })

     
  }

My Full Page Code

import "./styles.css";
import axios from 'axios'
import ReactSearchBox from 'react-search-box'
import {useEffect, useState} from 'react'

export default function App() {

  let [data, setData] = useState()
  
  useEffect(onMount,[])

  function onMount(){
      
      axios.get('https://restcountries.com/v3.1/all').then(res=>{
        
        let arr = res.data.map((c)=>{
          return {key:c.name.common, value: c.name.common}
        })
        setData(arr)
      })

     
  }
  return (
    <div className="App">
      <h1>Countries</h1>
      {data.length>0 ? <ReactSearchBox
        placeholder="Placeholder"
        value="Doe"
        data={data}
        callback={(record) => console.log(record)}
      />: null}
    </div>
  );
}

Picture of Error

在此处输入图像描述

The react-search-box you're using uses React 17 . This is not compatible with React 18. As a result, once your data state is populated and the <ReactSearchBox is invoked, an error is thrown.

Your code itself is fine - it's the dependency that's the problem.

Either:

  • fork react-search-box and upgrade it to make it compatible with React 18, and use that version instead
  • downgrade your React version to React 17
  • come up with your own search box to remove the dependency on react-search-box
  • wait for react-search-box's maintainers to update to React 18

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