📡

React.js API Calls Explained

Aug 27, 2024

React.js API Calls Tutorial

Introduction

  • Overview of calling APIs in React.js
  • Sending data to the server and receiving it back
  • Using a local project hosted on localhost:2001 for demonstration

Project Structure

  • Simple structure with a main component named App
  • Rendering author list from the state
  • Initial list of authors stored in a simple array (to be replaced with data fetched from backend later)

Fetching Data

Best Practices

  • Use the useEffect hook for fetching data when the component mounts
  • If using class components, use componentDidMount

Fetching Logic

  1. Create an asynchronous function fetchData
  2. Use the fetch API to request data:
    • Pass the URL to fetch from as the first argument
    • Store the response in a variable result
  3. Convert the response to JSON:
    • result.json()
  4. Update the state with the fetched authors using setAuthors
  5. Call fetchData inside useEffect

Code Example

useEffect(() => { const fetchData = async () => { const result = await fetch('http://localhost:2001/authors'); const json = await result.json(); setAuthors(json); }; fetchData(); }, []);

Handling Submissions

Adding New Authors

  • On pressing the submit button, send a new author to the server:
  1. Define the new author data (without an ID)
    • Example:
      • Avatar: avatar_url
      • Full Name: User 4
  2. Use fetch to POST data:
    • Specify the API endpoint and method (POST)
    • Set headers (Content-Type: application/json)
    • Convert data to a JSON string
  3. Use result.json() to process the response

Updating UI Without Refresh

  • To update the UI without refreshing the page:
    • Update the state by combining previous values with the new author data

Code Example for Add Author

const addAuthor = async () => { const newAuthor = { avatar: 'avatar_url', full: 'User 5' }; const result = await fetch('http://localhost:2001/authors', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(newAuthor), }); const json = await result.json(); setAuthors(prevAuthors => [...prevAuthors, json]); };

Conclusion

  • Successfully demonstrated how to call APIs in React.js and manage state
  • Encouragement to leave feedback and suggestions for future tutorials
  • Thank you for watching!