0

I have a question how to tell useEffect to wait for text which comes from search input?
API contains lots of objects and i want to fetch one of them .

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const Search = () => {
    const [text, setText] = useState('');
    const [object, setObject] = useState(null);

    useEffect(() => {
        axios.get(`https://api/${text}`)
            .then(res => {
                setObject(text)
                console.log(object)
            })
            .catch(err => {
                console.log(err)
            })
    })

    const onChange = e => setText(e.target.value);

    return (
        <div>
            <form className="some-class">
                <input type="text" value={name} className="some-class" placeholder="I need information about..." onChange={onChange}/>
                <input type="submit" className="some-class" value="Search"/>
            </form> 
        </div>
        )
    }
    export default Search;
Bembnias
  • 21
  • 3

2 Answers2

3

If you want it to happen when the button is clicked, then you don't need an effect, you need a click handler.

const Search = () => {
    const [text, setText] = useState('');
    const [object, setObject] = useState(null);

    const onClick = () => {
        axios.get(`https://api/${text}`)
            .then(res => {
                setObject(text)
            })
            .catch(err => {
                console.log(err)
            })
    })

    const onChange = e => setText(e.target.value);

    return (
        <div>
            <form className="some-class">
                <input type="text" value={name} className="some-class" placeholder="I need information about..." onChange={onChange}/>
                <input onClick={onClick} type="submit" className="some-class" value="Search"/>
            </form> 
        </div>
    )
}
export default Search;

PS: my example uses setObject(text) since that's what you had in your code, but that's probably a typo. You may have meant setObject(res.data)

Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
1

If you want it to be done when you mount the compoennt call the useEffect like this:

useEffect(() => {
        axios.get(`https://api/${text}`)
            .then(res => {
                setObject(text)
                console.log(object)
            })
            .catch(err => {
                console.log(err)
            })
    }, []);

That should do, as when you get the render the api call will be done. If you want it to be done on change a state just set the parameter inside the [] at the end of the useEffect.

Carlos Saiz Orteu
  • 1,735
  • 1
  • 10
  • 18