Different ways to fetch data in Javascript

Hi, here the different ways that you can use for fetch data of course this will be depend of your project requirement.

1 Way

We can use Javascript fetch API to get data from server

const url = "/todos";  
fetch(url)
 .then(resp => resp.json())
 .then(data => {
    console.log("data---->", data);
    setData(data); // Saving data response 
                   // into react local state
});

Note: If you want to update data into the server, you can use the fetch method to like this:

fetch("/todos", {
  method: "post",
  headers: {
    "content-type": "application/json"
  },
  body: JSON.stringify(data)
})
  .then(resp => resp.json())
  .then(data => {
    setData(data);
});
Fetch - already returns a promise

2  Way

We can use an external library called “Axios

 A) Way a

    // Importing axios library
    import axios from 'axios';
    
    // To avoid the .then method mean 
    // I'm resolving the promise
    const fetchAsync = async () => {
      // Request data using axios library
      // Note: the time that takes to resolve 
      // the rquest is Pending state.
      try {
        const response = await axios.get('https://restcountries.eu/rest/v2/all'); // Fulfilled
        setCountries(response.data);
      } catch (error) { // Rejected
        console.log('error => ', error.message)
      }
    }

 fetchAsync(); 
   

B) Way b

 // Importing axios library
    import axios from 'axios';

      const request = axios.get('https://restcountries.eu/rest/v2/all');
      request.then(res => {
          setCountries(res.data);
      })
      .catch(err => {
          console.log(err.message);
      })

3  Way

If we are using GraphQL we can implement this way to fetch data with queries

// Dependencies
import { gql } from 'apollo-boost'

export default gql`
  query getPosts(
    $orderBy: String,
    $direction: String,
    $limit: Int,
    $offset: Int
  ) {
    getPosts(
      options: {
        orderBy: $orderBy,
        direction: $direction,
        limit: $limit,
        offset: $offset
      }
    ) {
      id
      title
      slug
      content
      readingTime
      language
      published
      userId
      createdAt
      tags {
        name
      }
    }
  }
`
// Dependencies
import React, { createContext, useState } from 'react'
import { useApolloClient } from 'react-apollo-hooks'

// Queries
import GET_POSTS from '@graphql/blog/getPosts.query'

// Getting data
const { data } = await query({
 query: GET_POSTS,
  variables: {
    orderBy: 'createdAt',
    direction: 'DESC',
    limit: 10,
      offset: page === 1 ? 0 : (page - 1) * 10
  }
})

Note: If you want to update data you need to use a mutation, this way

// Dependencies
import { gql } from 'apollo-boost'

export default gql`
  mutation createPost(
    $title: String!,
    $slug: String!,
    $content: String!,
    $readingTime: String!,
    $language: String!,
    $published: Boolean!,
    $userId: UUID!,
    $tags: [TagsInput],
  ) {
    createPost(
      input: {
        title: $title,
        slug: $slug,
        content: $content,
        readingTime: $readingTime,
        language: $language,
        published: $published,
        userId: $userId,
        tags: $tags
      }
    ) {
      id
      title
      slug
      content
      readingTime
      language
      published
      userId
      tags {
        name
      }
    }
  }
`
// Mutations
import CREATE_POST from '@graphql/blog/createPost.mutation'

const { errors, data } = await mutate({
  mutation: CREATE_POST,
  variables: values,
  errorPolicy: 'all'
})

Here the Source example.

By Cristina Rojas.