React Hooks, JWT-Fetch Example

We have two states. First one is user and second one is list. In first state we are holding our user_token, token_type and expiration values.

Basically, we are running first useEffect when the page loads. It’s similar with ComponentDidMount(). We are being sure that user state is at is first state by checking with if block. Then first useEffect changes the user state by fetching user values to user state. Second useEffect is watching for changes in user state so, when user state changes it’s firing up second useEffect and it fetches our list. Also we are surrounding fetch with if block for being sure that second useEffect is not fired up when page loads first.

List holding only id and title in this example.

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

function App() {

  const [user, setUser] = useState(false)
  const [list, setList] = useState([])

  useEffect(() => {
    if (user === false) {
      let data = { email: 'LOGIN_USERNAME', password: 'LOGIN_PASSWORD' }
      fetch("LOGIN_URL",
        {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(data)
        }).then(res => res.json())
        .then(data => {
          setUser(data)
        }
        ).catch(err => console.log(err))
    }
  }, [user])


  useEffect(() => {
    if (user !== false) {
      fetch("FETCH_LIST_URL", {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${user.access_token}`
        }
      }).then(res => res.json()).then(data => {
        setList([...list, data])
      }).catch(err => console.log(err))
    }
  }, [user])

  return (
    <>
      <h1>List</h1>
      {list !== undefined ? list.map(list => (<li key={list.id}>{list.title}</li>)) : "null"}
    </>
  );
}

export default App