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?
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]
コメントを追加