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

Time:06-26

  • 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

enter image description here

CodePudding user response:

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
  • Related