skip to Main Content

I’m consuming an API, my question is, how can I show only what the JSON has in position 0, for example.

If in my Promise I have a console.log(res[0]), it shows the first data, but if I have it here:
setDB(res[0]); It is not working…

I’m very noob with React and I’m practising this… Sorry for the noob question.

What I want to do is to have a table where it only shows one data of the JSON, and have two buttons to go next or prev… So I only need to show the first one.

This is How I’m consuming it:

function App() {
  const [db, setDB] = useState(null)

  const url = 'myAPI';

  useEffect(() => {
    generateRequest.get(url)
      .then((res) => {        
        //console.log(res[0]); --> shows first data
        setDB(res);        
      })
      .catch(err => {        
        setDB([])
      })
  }, []);    

  return (
    <>
      {db && <Users db={db}/>}
    </>
  )
}

2

Answers


  1. You are storing the fetched data using setDB(res), yet, you mentioned that you only want to show the first data from the JSON response and have buttons to navigate to the next or previous data.

    You can modify your code as below. Please note that this code is so simplified. In usual, I would use a library such as MUI, etc.

    function App() {
      ...
      const [currentIndex, setCurrentIndex] = useState(0);
    
      useEffect(() => {
        generateRequest.get(url)
          .then((res) => {
            setDB(res);
          })
          .catch(err => {
            setDB([]);
          });
      }, []);
    
      const handleNext = () => {
        if (currentIndex < db.length - 1) {
          setCurrentIndex(currentIndex + 1);
        }
      };
    
      const handlePrev = () => {
        if (currentIndex > 0) {
          setCurrentIndex(currentIndex - 1);
        }
      };
    
      return (
        <>
          {db && db.length > 0 && (
            <div>
              <button onClick={handlePrev} disabled={currentIndex === 0}>Prev</button>
              <table>
                <thead>
                  <tr>
                    <th>Data</th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td>{db[currentIndex]}</td>
                  </tr>
                </tbody>
              </table>
              <button onClick={handleNext} disabled={currentIndex === db.length - 1}>Next</button>
            </div>
          )}
        </>
      );
    }
    

    In this updated code, there is a new state currentIndex (zero as initial value) that keeps track of the current index in the db array.

    There are new methods handleNext and handlePrev, which update currentIndex accordingly to navigate to the next or previous data.

    Login or Signup to reply.
  2. It seems like you may need to update your code to use setDB(res[0]) instead of setDB(res). The former will retrieve the first record of the response body, which is typically what you want to display. Just be aware of this when working with the parameter inside the function.

    Additionally, I recommend using fetch() or Axios instead of generateRequest(). These methods are more commonly used. Also, they both require json() to parse the response body and access data elements.

    useEffect(() => {
       fetch('myAPI')
          .then((res) => res.json())
          .then((data) => {
             for (item in data) { // this will iterate through all the items, you may not need the for loop
                console.log(data[item]);
                setDB(data[item]);
             }
          })
          .catch((err) => {
             console.log(err.message);
          });
    }, []);
    

    https://stackabuse.com/get-http-request-in-react/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search