sojinLee
sojinLee

Reputation: 63

An empty array is returned when using useState in React

function Search(){
    const [title, setTitle]=useState('');
    const [book, setBook]=useState([]);
    
    const onChange=(e)=> setTitle(e.target.value);

    const headers= {};
    const getBookList= async ()=>{
        try{
            const response=await axios.get(`https://dapi.kakao.com/v3/search/book?target=title&query=${title}`, {headers});
            setBook(response.data.documents);
            console.log(response.data.documents);
        }catch(e){
            console.log(e);
        }
    };

    useEffect(()=>{
        getBookList();
        console.log(book);
    },[]);

    return (
        <div>
            <input value={title} onChange={onChange}></input>
            <button onClick={getBookList}>push</button>
            <div>{book[0]}</div>
        </div>
    );
}

export default Search;

response.data.documents holds data like photos:

However, the variable called book does not contain anything. book[0] outputs nothing. How can we process this data?

Upvotes: 0

Views: 2094

Answers (1)

Oliver Ilmj&#228;rv
Oliver Ilmj&#228;rv

Reputation: 341

The promise has not been fulfilled yet when you are logging it. try like this

// two useeffect hooks, one for logging, other for populating
useEffect(()=>{
        getBookList();
},[]);

useEffect(()=>{
        console.log(book);
},[book]);

the whole component might look like this

function Search(){
  const [title, setTitle]=useState('');
  const [book, setBook]=useState([]);
  
  const onChange=(e)=> setTitle(e.target.value);

  const headers= {};
  const getBookList= ()=>{
    axios.get(`https://dapi.kakao.com/v3/search/book?target=title&query=${title}`, {headers}).then(res => {
      setBook(res.data.documents)
    })
  };

  useEffect(()=>{
    getBookList()
  },[]);

  return (
      <div>
          <input value={title} onChange={onChange}></input>
          <button onClick={getBookList}>push</button>
          <div>{book.length > 0 ? JSON.stringify(book[0]) : ""}</div>
      </div>
  );
}

export default Search;

Note: {book.length > 0 ? book[0] : ""} is for checking if the array has been populated, since at the moment the component loads, the request response hasnt arrived yet

Edit: do not render json in the dom, JSON.stringify(book[0]) is the correct way, if you want to see the json data.

Upvotes: 1

Related Questions