简体   繁体   中英

Trying to use React Hook and Axios to display data from my API but nothing is rendering

Designer creating my first full-stack app to better understand more complex development concepts. I'm currently unable to get data displayed in the browser from my React app. However, unlike previous roadblocks, I'm not getting an actual error to search, so I'm not exactly sure where I've got a problem.

The client and server seem to load up fine (localhost:3000 and:8000 respectively) but my very simple app.js client doesn't display anything. In the terminal window I do see:

"Executing (default): SELECT "id", "title", "subtitle", "lyric", "published", "createdAt", "updatedAt" FROM "playlists" AS "playlists"; GET /api/playlists 200 49.085 ms - 463

So it seems like the GET request might be working, but I'm staring at a blank white screen in the browser. Any help would be appreciated. Happy to provide more info but I'll include the app.js below.

App.js

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

function App() {
  const [data, setData] = useState({ playlists: [] });

  useEffect(() => {
    const fetchData = async () => {
      const result = await axios('http://localhost:8000/api/playlists');
      setData(result.data);
    };
    fetchData();
  }, [] );

  return (
    <div>
      All Playlists
       <ul>
        {data.playlists && data.playlists.map(playlist => (
          <li key={playlist.id}>
           {playlist.title}{playlist.subtitle}
          </li>
        ))}
      </ul>
    </div>
  );
}

export default App;

You have to set request method in axios :

So if it is GET :

const result = await axios.get('http://localhost:8000/api/playlists');

I believe this is an CORS issue. I don't know for other languages, but if you're using experss, you can easily rectify it by adding a CORS Middleware.

Yarn add CORS

And in your index file

Const cors = require(`cors`)

//After express initialization

app.use(cors)

You can extend the configuration of course, but just doing this will solve your problem.

https://www.npmjs.com/package/cors

You don't need to have object with array in your initial state value as you can have multiple useStates in same component. You can set initial state value to empty array. I would rename const [data, setData] = useState([]); to const [playlists, setPlaylists] = useState([]) to make it more readable. Now in your map you can just use:

  <ul>
    {playlists.map(playlist => (


        <li key={playlist.title}>
          {playlist.title}
          {playlist.subtitle}
        </li>

    ))}
  </ul>

Your whole component would look like:

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

function App() {
  const [playlists, setPlaylists] = useState([]);


  useEffect(() => {
    const fetchData = async () => {
      const result = await axios(
      'http://localhost:8000/api/playlists'
    );
    setPlaylists(result.data);
  };
    fetchData();
  }, []);

  return (
    <div>
      All Playlists
      <ul>
        {playlists.map(playlist => (


            <li key={playlist.title}>
              {playlist.title}
              {playlist.subtitle}
            </li>

        ))}
      </ul>
    </div>
  );
}

export default App;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM