How to get distinct values from an array of fetch API output

pranami

I am trying to fetch the json data from an API and split its value and populate the value in my React project.The code for server API is as shown below:

const clone = require('clone')
const config = require('./config')

let db = {}

const defaultData = {
  categories: [
      {
        name: 'react',
        path: 'react'
      },
      {
        name: 'redux',
        path: 'redux'
      },
      {
        name: 'udacity',
        path: 'udacity'
      }
  ]
}

function getData (token) {
  //Each token has it's own copy of the DB. The token in this case is like an app id.
  let data = db[token]
  //This populates the default user data if there isn't any in the db.
  if (data == null) {
    data = db[token] = clone(defaultData)
  }
  return data
}

function getAll (token) {
  return new Promise((res) => {
    res(getData(token))
  })
}

module.exports = {
  getAll
}

And, I am trying to get the data from the above API with the code shown below:

readableAPI.js

const url = "http://localhost:3001/"

let token = localStorage.token
if (!token)
  token = localStorage.token = Math.random().toString(46).substr(-8)

const headers = {
  'Accept': 'application/json',
  'Authorization': token
}

export const getCategories = () =>
fetch('http://localhost:3001/categories', {headers})
  .then(res => res.json())
  .then(data => console.log(data))

Then in my React component, I am trying to get the result of the API as shown below:

import * as readableAPI from './readableAPI.js'

class App extends Component {

componentDidMount() {
  readableAPI.getCategories().then((category) => 
  category.map( value => console.log(value.name)))
}

...

}

Now the problem I am facing is: in the above code in the componentDidMount() lifecycle method,I am able to fetch the json data with the code given below:

componentDidMount() {
    readableAPI.getCategories()
}

The above code gives the array of the 3 categories:

{categories: Array(3)}
   0: {name: "react", path: "react"}
   1: {name: "redux", path: "redux"}
   2: {name: "udacity", path: "udacity"}

But, if I try to map over the array and get the individual values using the below code,I get the output as undefined.

componentDidMount() {
      readableAPI.getCategories().then((category) => 
      category.map( value => console.log(value.name)))
    }

I want to get the values of each categories so I can use the name of the category available in the server and display it in my react component.Where am I going wrong.Can anyone please guide me with this issue?

Sagiv b.g

You are not returning anything from the fetch:

fetch('http://localhost:3001/categories', {headers})
  .then(res => res.json())
  .then(data => console.log(data)) // you should return the data (or promise) here

This is how you write the fetch (run it):

var root = 'https://jsonplaceholder.typicode.com';
const getCategories = () =>
  fetch(root + '/posts/1', {
    method: 'GET'
  })
  .then(res => res.json())
  .then(data => console.log('inside the fetch - ', data))


getCategories().then((category) => {
  console.log('outside the fetch - ', category);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/2.0.3/fetch.min.js"></script>

This is the fix (run it):

var root = 'https://jsonplaceholder.typicode.com';
const getCategories = () =>
  fetch(root + '/posts/1', {
    method: 'GET'
  })
  .then(res => res.json())
  .then(data => {
    console.log('inside the fetch - ', data);
    // you must return the data!
    return data;
  })


getCategories().then((category) => {
  console.log('outside the fetch - ', category);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/2.0.3/fetch.min.js"></script>

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

How to get distinct values from an array in mongoDB and group them by ID

分類Dev

Get distinct values of child array as additional property

分類Dev

How to get the value from previous value in json using fetch api?

分類Dev

How to get number of distinct values ? mysql

分類Dev

How to get the combination of array values from nested arrays in an array of objects

分類Dev

how to get the array output from a js function in java 8?

分類Dev

Distinct values from array based on a part of the string in JS

分類Dev

How to get the values of a column from a table in jQuery into a multidimentional array

分類Dev

get a set of values from an array

分類Dev

How to fetch data from array and insert to database

分類Dev

Get values from array and using the values in a program

分類Dev

Fetch unique values from array of objects based on dynamically passed property

分類Dev

How to get text values to an array?

分類Dev

MongoDB get all distinct values

分類Dev

How to get values in array of array in angular?

分類Dev

phpexcel can't get values from array

分類Dev

how to get fetch data from sqlite from the given string?

分類Dev

How to get the value type from an output iterator?

分類Dev

How to get arrays on output from MongoDB aggregate

分類Dev

How can I show an array from a fetch() on a <FlatList>?

分類Dev

Angular: How to use a Service to fetch data from server and store in an array?

分類Dev

How to make fetch data from web api Angular 6

分類Dev

How to fetch the latest log events from the CloudWatch API?

分類Dev

How to use react native fetch() to retrieve malformed json from api

分類Dev

How to correctly fetch data from API endpoint with multiple parameter in python?

分類Dev

How to correctly fetch data from API endpoint with multiple parameter in python?

分類Dev

Create distinct values in array - not yielding expected results

分類Dev

How to fetch or get data from Cloud Firestore Firebase in android

分類Dev

How to get common values from 4 multidimensional arrays using array_intersect

Related 関連記事

  1. 1

    How to get distinct values from an array in mongoDB and group them by ID

  2. 2

    Get distinct values of child array as additional property

  3. 3

    How to get the value from previous value in json using fetch api?

  4. 4

    How to get number of distinct values ? mysql

  5. 5

    How to get the combination of array values from nested arrays in an array of objects

  6. 6

    how to get the array output from a js function in java 8?

  7. 7

    Distinct values from array based on a part of the string in JS

  8. 8

    How to get the values of a column from a table in jQuery into a multidimentional array

  9. 9

    get a set of values from an array

  10. 10

    How to fetch data from array and insert to database

  11. 11

    Get values from array and using the values in a program

  12. 12

    Fetch unique values from array of objects based on dynamically passed property

  13. 13

    How to get text values to an array?

  14. 14

    MongoDB get all distinct values

  15. 15

    How to get values in array of array in angular?

  16. 16

    phpexcel can't get values from array

  17. 17

    how to get fetch data from sqlite from the given string?

  18. 18

    How to get the value type from an output iterator?

  19. 19

    How to get arrays on output from MongoDB aggregate

  20. 20

    How can I show an array from a fetch() on a <FlatList>?

  21. 21

    Angular: How to use a Service to fetch data from server and store in an array?

  22. 22

    How to make fetch data from web api Angular 6

  23. 23

    How to fetch the latest log events from the CloudWatch API?

  24. 24

    How to use react native fetch() to retrieve malformed json from api

  25. 25

    How to correctly fetch data from API endpoint with multiple parameter in python?

  26. 26

    How to correctly fetch data from API endpoint with multiple parameter in python?

  27. 27

    Create distinct values in array - not yielding expected results

  28. 28

    How to fetch or get data from Cloud Firestore Firebase in android

  29. 29

    How to get common values from 4 multidimensional arrays using array_intersect

ホットタグ

アーカイブ