0

Please refer the image

When I change the content of input field and log it using console.log(e.target.value) then updated value gets logged but when i use setContent(e.target.value) it is setting the content's value to previous value of input

const Search=()=>{
    const[content,setContent]=useState([]);
    const[todos,setTodos]=useState([]);

    useEffect(() =>{
        document.title="Search";
    },[])



    //searching in database
    const searchDatabase=(content)=>{
        axios.get(`${base_url}/search/${content}`).then(
            (response)=>{
                setTodos(response.data);
            },
            ()=>{
                console.log("Database Down")
            }
        )
    }

return (
        <div>
            <Row>
                <Form className="form-inline mt-2 mb-4">
                    <FaSearch/>
                    <Input id="searchBox" className="ml-3" type="text"  
                    onChange={(e)=>{
                        console.log("current value: "+e.target.value);

                        setContent(e.target.value);

                        console.log("content value: "+content);

                        searchDatabase(content) 
                    }}
                    />


                </Form>
            </Row>
        </div>
       )
}

Thanks for help..

  • `content` is a local `const` with the value from the old render. It will never change. Calling `setContent` asks react to rerender your component, but code from the old render can't access local variables that will be created on the next render. – Nicholas Tower Mar 13 '22 at 20:20

1 Answers1

0

add function onChange event and use useEffect for do something on change of your content

const Search=()=>{

    const [content,setContent]=useState([]);
    const [todos,setTodos]=useState([]);


   const onSearchChange = (e) => {
    let inputUpdated = {
      ...content,
      [e.target.name]: e.target.value,
    };
    setContent(Updated);

    // check with console.log
    console.log(inputUpdated);
  };


    //searching in database
    const searchDatabase=(content)=>{
        axios.get(`${base_url}/search/${content}`).then(
            (response)=>{
                setTodos(response.data);
            },
            ()=>{
                console.log("Database Down")
            }
        )
    }



    useEffect(() =>{
        document.title="Search";
    },[ ])


    // On Content Change
    useEffect(() =>{
        searchDatabase(content); //Do as you want
    },[setContent])




return (
        <div>
            <Row>
                <Form className="form-inline mt-2 mb-4">
                    <FaSearch/>
                    <Input id="searchBox" className="ml-3" type="text"  
                           onChange={onSearchChange}
                    />

                </Form>
            </Row>
        </div>
       )
}
GMKHussain
  • 3,342
  • 1
  • 21
  • 19