skip to Main Content

Can someone help me translate these axios requests into fetch requests? I am having trouble transfering the token in axios. I think it would work in fetch but I am having trouble rewriting the request.

import React, { useState, useEffect,useContext } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import axios from 'axios';
import AuthContext from '../context/AuthContext';

function FileUpload({ setUploads = () => {} }) {
  const navigate = useNavigate();
  const { id } = useParams();
  const [photo, setphoto] = useState(null);
  const { authTokens, logoutUser } = useContext(AuthContext);
  const accesstoken = String(authTokens.access);

  useEffect(() => {
    if (id) {
      axios.get(`http://xxxxxxx:8000/api/upload/${id}/`
        ).then((response) => {
        setphoto(response.data.photo.name);

      });
    }
  }, [id]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    const formData = new FormData();
    formData.append('photo', photo);

    try {
      let response;
      if (id) {
        response = await axios.patch(`http://xxxxxxx:8000/api/upload/${id}/`, formData);
        setUploads((prevUploads) =>
          prevUploads.map((upload) => (upload.id === response.data.id ? response.data : upload))
        );
        alert(`file updated successfully!`, navigate(`/upload/${response.data.id}`));

      } else {
        response = await axios.post('http://xxxxxx:8000/api/upload/', formData);
        setUploads((prevUploads) => [response.data, ...prevUploads]);
        alert('Upload created successfully!', navigate('/'));
      }

      setphoto(null);
    } catch (error) {
      console.error(error);
    }
  };


  return (
    <div className="container mx-auto px-4">
    <form onSubmit={handleSubmit}>
      <div className="mb-4">
        <label htmlFor="photo" className="block font-medium text-gray-700">
        photo/file
        </label>
        <input
          type="file"
          name="photo"
          id="photo"
          onChange={(e) => setphoto(e.target.files[0])}
          className="border border-gray-400 rounded w-full px-3 py-2 mt-1 text-gray-900"
        />
      </div>
      <div className="mt-6">
        <button
          type="submit"
          className="bg-blue-500 text-white font-medium py-2 px-4 rounded hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-600 focus:ring-offset-2"
        >
          {id ? 'Update Upload' : 'Create Upload'}
        </button>
      </div>
    </form>
  </div>
);

}

export default FileUpload;

I have tried to represent the token system wide with axios interceptor.
I have tried to include token in each request with

`'Authorization':'Bearer ' + String(authTokens.access).`

I have one request written in fetch and it works with

`'Authorization':'Bearer ' + String(authTokens.access).`

2

Answers


  1. Below is how you would convert the given Axios requests to fetch requests in JavaScript. Note that for both GET and PATCH/POST requests with fetch, we’re adding the 'Authorization': 'Bearer ' + accesstoken header for token-based authentication.

    import React, { useState, useEffect, useContext } from 'react';
    import { useNavigate, useParams } from 'react-router-dom';
    import AuthContext from '../context/AuthContext';
    
    function FileUpload({ setUploads = () => {} }) {
      const navigate = useNavigate();
      const { id } = useParams();
      const [photo, setPhoto] = useState(null);
      const { authTokens, logoutUser } = useContext(AuthContext);
      const accesstoken = authTokens.access;
    
      // Convert axios.get to fetch
      useEffect(() => {
        if (id) {
          fetch(`http://xxxxxxx:8000/api/upload/${id}/`, {
            headers: {
              'Authorization': 'Bearer ' + String(accesstoken),
            }
          })
          .then(response => response.json())
          .then(data => {
            setPhoto(data.photo.name);
          });
        }
      }, [id, accesstoken]);
    
      const handleSubmit = async (e) => {
        e.preventDefault();
        const formData = new FormData();
        formData.append('photo', photo);
    
        try {
          let response;
          let responseData;
          
          const options = {
            method: id ? 'PATCH' : 'POST',
            headers: {
              'Authorization': 'Bearer ' + String(accesstoken),
            },
            body: formData,
          };
    
          const url = `http://xxxxxxx:8000/api/upload/${id ? `${id}/` : ''}`;
    
          // Convert axios.post/axios.patch to fetch
          response = await fetch(url, options);
          responseData = await response.json();
    
          if (id) {
            setUploads((prevUploads) =>
              prevUploads.map((upload) => (upload.id === responseData.id ? responseData : upload))
            );
            alert(`File updated successfully!`);
            navigate(`/upload/${responseData.id}`);
          } else {
            setUploads((prevUploads) => [responseData, ...prevUploads]);
            alert('Upload created successfully!');
            navigate('/');
          }
    
          setPhoto(null);
    
        } catch (error) {
          console.error(error);
        }
      };
    
      // ... rest of your component code remains unchanged ...
    }
    
    export default FileUpload;
    

    Remember to handle the possibility that the fetch could fail due to network errors by using a .catch() after the .then() chains or using try/catch appropriately within an async function. This ensures that network errors do not go uncaught.

    Also ensure that the server handling these requests is properly set up to handle CORS (Cross-Origin Resource Sharing) when dealing with client-side requests from a different origin.

    Login or Signup to reply.
  2. Try this.

    import React, { useState, useEffect, useContext } from 'react';
    import { useNavigate, useParams } from 'react-router-dom';
    import AuthContext from '../context/AuthContext';
    
    function FileUpload({ setUploads = () => {} }) {
      const navigate = useNavigate();
      const { id } = useParams();
      const [photo, setPhoto] = useState(null);
      const { authTokens, logoutUser } = useContext(AuthContext);
      const accessToken = String(authTokens.access);
    
      useEffect(() => {
        if (id) {
          fetch(`http://xxxxxxx:8000/api/upload/${id}/`, {
            method: 'GET',
            headers: {
              'Authorization': 'Bearer ' + accessToken,
            },
          })
          .then(response => response.json())
          .then(data => {
            setPhoto(data.photo.name);
          })
          .catch(error => {
            console.error('Error fetching photo:', error);
          });
        }
      }, [id, accessToken]);
    
      const handleSubmit = async (e) => {
        e.preventDefault();
        const formData = new FormData();
        formData.append('photo', photo);
    
        try {
          let response;
          if (id) {
            response = await fetch(`http://xxxxxxx:8000/api/upload/${id}/`, {
              method: 'PATCH',
              headers: {
                'Authorization': 'Bearer ' + accessToken,
              },
              body: formData,
            });
          } else {
            response = await fetch('http://xxxxxx:8000/api/upload/', {
              method: 'POST',
              headers: {
                'Authorization': 'Bearer ' + accessToken,
              },
              body: formData,
            });
          }
    
          const data = await response.json();
          if (!response.ok) {
            throw new Error(data.message || 'Something went wrong');
          }
    
          if (id) {
            setUploads((prevUploads) =>
              prevUploads.map((upload) => (upload.id === data.id ? data : upload))
            );
            alert('File updated successfully!');
            navigate(`/upload/${data.id}`);
          } else {
            setUploads((prevUploads) => [data, ...prevUploads]);
            alert('Upload created successfully!');
            navigate('/');
          }
    
          setPhoto(null);
        } catch (error) {
          console.error('Error uploading photo:', error);
        }
      };
    
      return (
        <div className="container mx-auto px-4">
          <form onSubmit={handleSubmit}>
            <div className="mb-4">
              <label htmlFor="photo" className="block font-medium text-gray-700">
                Photo/File
              </label>
              <input
                type="file"
                name="photo"
                id="photo"
                onChange={(e) => setPhoto(e.target.files[0])}
                className="border border-gray-400 rounded w-full px-3 py-2 mt-1 text-gray-900"
              />
            </div>
            <div className="mt-6">
              <button
                type="submit"
                className="bg-blue-500 text-white font-medium py-2 px-4 rounded hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-600 focus:ring-offset-2"
              >
                {id ? 'Update Upload' : 'Create Upload'}
              </button>
            </div>
          </form>
        </div>
      );
    }
    
    export default FileUpload;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search