Why am I getting 2 times data null and data? - javascript

I am getting two time data null and data, what is my problem? And, why should I write two time data? Is it problem with json? Can anybody help me?
Contex.js
class ProviderWrapper extends Component {
constructor(props) {
super(props);
this.state = {
data: null,
isLoading: false
};
}
componentDidMount() {
this.setState({ isLoading: true });
fetch(URL + JSON_PATH)
.then(response => response.json())
.then(data => this.setState({ data, isLoading: false }));
}
render() {
const { children } = this.props;
return <Context.Provider value={this.state}>{children}</Context.Provider>;
}
}
test.js
import React, { Component } from "react";
import { Ctx } from "../Context/Context";
class Menu extends Component {
static contextType = Ctx;
render() {
const { data } = this.context;
console.log("data",data)
return (
<MenuWrapper>
{data && data.name}
</MenuWrapper>
);
}
}

data in ProviderWrapper starts out null and you don't start the fetch until componentDidMount, so data will be null for at least one call to render. You haven't shown what Menu and ProviderWrapper are both in, but Menu's render will be called whenever it needs to render, regardless of whether the fetch is done. It's not at all surprising that it does that at least once, and twice doesn't seem odd either.
Menu needs to be able to handle it when data is null (which it already seems to, so that's good).
A couple of side notes:
It's not the problem, but you're falling prey to a footgun in the fetch API: You need to check ok before calling json, details on my anemic little blog.
You're not handling errors at all. If the fetch fails for whatever reason, your ProviderWrapper is just left in the loading state forever. You need to handle errors.
Here's what that fetch call should look like:
fetch(URL + JSON_PATH)
.then(response => {
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
response.json();
})
.then(data => this.setState({ data, isLoading: false }))
.catch(error => {
// ...handle/show error here and clear the loading state...
});
(In my projects, I have a wrapper for fetch so I don't have to do that every time. Making HTTP errors fulfillments rather than rejections was a major mistake in the API.)

Related

Rendering data, fetched from an API in react-native

I am using React-Native and am having issues just getting data to render from an API, into the render function. I'm running node JS and express on one end to pull some data from a SQL database. This returns JSON that looks like this:
{"routines":[{"routine_id":1,"name":"Morning Routine","start_time":"2020-03-09T14:24:38.000Z","end_time":"2020-03-09T15:24:44.000Z","is_approved":0}]}
I want to loop through the routines key and print out each routine as components in React. I don't really care about what type of component that gets used, I just want to get the data. I've tried a few methods:
Method 1: Using componentDidMount with fetch:
constructor() {
super();
this.state = { routines: {} }
}
componentDidMount() {
fetch('http://localhost:3000/routines')
.then((response) => response.json())
.then((responseJson) => {
return responseJson;
})
.then( routines => {
this.setState({routines: routines});
})
.catch( error => {
console.error(error);
});
}
render() {
console.log(this.state)
render of this.state logs an empty object, despite the then(routines portion of the code returning the correct data.
Method 2: Putting everything in componentDidMount
async componentDidMount() {
const response = await fetch("http://localhost:3000/routines")
const json = await response.json()
console.log('json');
console.log(json);
const routines = json.routines
this.setState({routines})
}
Again, logging the state in render produces nothing while logging the json that gets returned from componentDidMount does return valid data.
Inside the render method i've also tried:
const { routines } = this.state;
And routines comes up as undefined.
Method 3: Directly calling a function to set the state.
constructor() {
super();
this.state = { routines: this.fetchData() }
}
This ends up returning some weird data:
{"routines": {"_40": 0, "_55": null, "_65": 0, "_72": null}}
I'm assuming it's because react native does not want me to do this.
I just want a simple way to fetch data from an API and display that data in render. I've gone through about four tutorials and all of them end up with undefined or objects set as the default value in the constructor in the render method. Am I going crazy? It feels like this is somehow impossible..?
You do everything right, just use state in render and you will see updates.
constructor() {
super();
this.state = { routines: [] }
}
render() {
const { routines } = this.state
return (
<View>
{routines.map(item => <Text>{item.name}</Text>)}
</View>
)
}
Since fetch is an async task the data this.setState({routines}) get's set after render() is executed. You can execute this.forceUpdate() after setting this.setState({routines}). This will re-execute render() when the data is set.
See: https://reactjs.org/docs/react-component.html#forceupdate
However, debugging mode can also be the culprit.
its may be because fetch call is async ,and your render method may try to use it before its loaded by the api call,
so your componentDidMount should be like
componentDidMount() {
this.setState({routines:null})
//fire an api call
fetch('http://localhost:3000/routines')
.then((response) => response.json())
.then((responseJson) => {
return responseJson;
})
.then( routines => {
this.setState({routines: routines});
})
.catch( error => {
console.error(error);
});
}
now inside your render function you should first confirm that routines is not null and have some valid values like
render(){
if(this.state.routines !==null){
//your code to render component
}else{
//your loading or error message
}
}

This.state property is considered "undefined"

I'm fetching data from my backend to my frontend. After I invoke
let data = response.json(), I then invoke const bartData = Object.entries(data). So, I'm creating an array that holds the key/value pairs of my original object. I then set the state of my component this.setState({allStations: bartData}), where the property allStations: []. This is where the problem comes up- I want visual confirmation that I'm geting the right data and manipulate it the way I want to so I invoke console.log(this.state.allStations[0]) and it gives me the correct contents but when I go further console.log(this.state.allStations[0][0], I get an error that states
this.state.allStations[0] is undefined
Why?
Also, I get that I'm putting an array inside of an array, which is why I was surprised that console.log(this.state.allStations[0])gave me the contents of the original array. Picture of console.log(this.state.allStations) this.state.allStations
constructor(){
super(props);
this.state = {
allStations: []
}
}
async getAllStations(){
try{
const response = await fetch(`/base-station-routes`);
let data = await response.json();
// console.log(response);
// let test = JSON.parse(bartData);
// console.log(test)
const bartData = Object.entries(data);
// console.log(bartData[0][0]) works
this.setState({
allStations: bartData
})
}catch(e){
console.log(`Error: ${e}`)
}
}
render(){
console.log(this.state.allStations[0]);
return( more stuff )
}
[1]: https://i.stack.imgur.com/hQFeo.png
In render function before console.log(this.state.allStations[0]) you should check the state value.
Render function executes before fetching data from backend, my suggestion to do this
if(this.state.allStations) && console.log(this.state.allStations[0])
Do a conditional render to prevent it from showing the array before response has been sent.
Add something like:
constructor(){
super(props);
this.state = {
isLoading: true,
allStations: []
}
}
You need to use React Lifecycles and stick Fetch inside:
componentWillMount(){
fetch('/base-station-routes') // Already Async
.then(res => res.json()) // Convert response to JSON
.then(res => this.setState({ isLoading: false, allStations: res})) // you can call it bartData, but I like to stick with res
.catch(err => { //.catch() handles errors
console.error(err)
})
}
and then in your Render:
render(){
return(
<div>
{this.state.isLoading ? <span>Still Loading</span> : // do a map here over your data}
</div>
)
}
This prevents doing anything with the data before your response is there.

React-Native async Array.map = undefined is not an Object

I try to create my first hybrid App with ReactNative. I have an issue with my Array.map…
class HomeScreen extends React.Component {
state = {
isLoading: false,
captured: false,
wished: false,
exchanged: false,
data: {}
};
async getPokemonFromApiAsync() {
try {
this.setState({isLoading: true});
let response = await fetch('https://pokeapi.co/api/v2/pokemon/?limit=0&offset=20');
return this.setState({
isLoading: false,
data: await response.json()
});
} catch (error) {
console.error(error);
}
(...)
componentWillMount() {
this.getPokemonFromApiAsync()
}
(...)
result = (result = this.state.data.results) => {
console.log('test', this.state.data);
return (
<View>
(...)
result.map( (item, index) => {
(...)
}
</View>
)
}
}
I don't understand, why my function getPokemonFromApiAsync is empty. iOS Simulator returns a TypeError: Undefined is not an object (evaluating 'result.map')
And when adding a constructor like:
constructor(props) {
super(props)
this.getPokemonFromApiAsync = This.getPokemonFromApiAsync.bind(this)
}
I have an many errors in console:
Warning: Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to this.state directly or define a state = {}; class property with the desired state in the %s component., setState, HomeScreen
For me, it's normal…
What is a good lifecycle for an asynchronous Http request?
Best way using axios library github link
npm install axios
Finally, weekly downloads are more than 4,000,000+ Github Starts 50,000+
Your error is caused by how you have set up your initial data in state.
You have set it up as:
state = {
isLoading: false,
captured: false,
wished: false,
exchanged: false,
data: {} // <- here you define it as an object, with no parameters
};
You should be setting it as an object with a results parameter`. So your initial state should look like
state = {
isLoading: false,
captured: false,
wished: false,
exchanged: false,
data: { results: [] } // <- here you should define the results inside the object
};
The reason you are getting the error:
TypeError: Undefined is not an object (evaluating 'result.map')
Is because on the initial render, before your fetch response has come back, it is trying to map over this.state.data.results which doesn't exist. You need to make sure that there is an initial value for results in the state.
That should stop the initial error, however you will have to make sure that what you are saving into state for data is also an array, otherwise you will continue to get the same error.
componentWillMount has been deprecated and you should be using componentDidMount.
Also as you are calling an async function inside you componentWillMount you should refactor it in the following way:
async componentDidMount() {
await this.getPokemonFromApiAsync()
}
So that the mounting doesn't occur until the fetch request has been completed.
I would also refactor your getPokemonFromApiAsync so that you get the response.json() before trying to set it into state. You also don't need the return statement as this.setState doesn't return anything.
async getPokemonFromApiAsync() {
try {
this.setState({isLoading: true});
let response = await fetch('https://pokeapi.co/api/v2/pokemon/?limit=0&offset=20');
let data = await response.json(); // get the data
this.setState({
isLoading: false,
data: data // now set it to state
});
} catch (error) {
console.error(error);
}
Snack:
Here is a very simple snack showing the code working https://snack.expo.io/#andypandy/pokemon-fetch
Code for snack:
export default class App extends React.Component {
state = {
isLoading: false,
captured: false,
wished: false,
exchanged: false,
data: { results: [] } // <- here you should define the results inside the object
};
getPokemonFromApiAsync = async () => {
try {
this.setState({ isLoading: true });
let response = await fetch('https://pokeapi.co/api/v2/pokemon/?limit=0&offset=20');
let data = await response.json(); // get the data
this.setState({
isLoading: false,
data: data // now set it to state
});
} catch (error) {
console.error(error);
}
}
async componentDidMount () {
await this.getPokemonFromApiAsync();
}
render () {
return (
<View style={styles.container}>
{this.state.data.results.map(item => <Text>{item.name}</Text>)}
</View>
);
}
}
A better way is to implement your state values when your promise is resolved using "then".
let response = fetch('https://pokeapi.co/api/v2/pokemon/?limit=0&offset=20')
.then((response) => {
this.setState({
isLoading: false,
data: response.json()
});
});
Maybe you can process your data (result.map) in the Promise callback and directly insert the result in your component.
And by the way, XHR calls are generally processed in the componentDidMount method.
The reason you are getting the error TypeError: Undefined is not an object (evaluating 'result.map') is that you are getting the result from this.state.data.results, but because data is async, at the first time it renders, data is {} (because you set it in the state), so data.result is undefined and you can't use .map() in a undefined.
To solve this, you can check if data.result is not undefined, before render it.
return (
<View>
(...)
result && result.map( (item, index) => {
(...)
}
</View>
)

fetching json in seperate component

I've made an application and want to add more components which will use the same json I fetched in "personlist.js", so I don't want to use fetch() in each one, I want to make a separate component that only does fetch, and call it in the other components followed by the mapping function in each of the components, how can make the fetch only component ?
here is my fetch method:
componentDidMount() {
fetch("data.json")
.then(res => res.json())
.then(
result => {
this.setState({
isLoaded: true,
items: result.results
});
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
error => {
this.setState({
isLoaded: true,
error
});
}
);
}
and here is a sandbox snippet
https://codesandbox.io/s/1437lxk433?fontsize=14&moduleview=1
I'm not seeing why this would need to be a component, vs. just a function that the other components use.
But if you want it to be a component that other components use, have them pass it the mapping function to use as a prop, and then use that in componentDidMount when you get the items back, and render the mapped items in render.
In a comment you've clarified:
I am trying to fetch the json once, & I'm not sure whats the best way to do it.
In that case, I wouldn't use a component. I'd put the call in a module and have the module expose the promise:
export default const dataPromise = fetch("data.json")
.then(res => {
if (!res.ok) {
throw new Error("HTTP status " + res.status);
}
return res.json();
});
Code using the promise would do so like this:
import dataPromise from "./the-module.js";
// ...
componentDidMount() {
dataPromise.then(
data => {
// ...use the data...
},
error => {
// ...set error state...
}
);
}
The data is fetched once, on module load, and then each component can use it. It's important that the modules treat the data as read-only. (You might want to have the module export a function that makes a defensive copy.)
Not sure if this is the answer you're looking for.
fetchDataFunc.js
export default () => fetch("data.json").then(res => res.json())
Component.js
import fetchDataFunc from './fetchDataFunc.'
class Component {
state = {
// Whatever that state is
}
componentDidMount() {
fetchFunc()
.then(res => setState({
// whatever state you want to set
})
.catch(err => // handle error)
}
}
Component2.js
import fetchDataFunc from './fetchDataFunc.'
class Component2 {
state = {
// Whatever that state is
}
componentDidMount() {
fetchFunc()
.then(res => setState({
// whatever state you want to set
})
.catch(err => // handle error)
}
}
You could also have a HOC that does fetches the data once and share it across different components.

Refactoring breaks initial state

React (from create-react-app) with MobX. Using axios for async backend API calls.
This code works. The initial state (array of issues) is populated, and the webpage presenting this component renders with initial content from state.
import { observable, computed, autorun, reaction } from 'mobx'
import axios from 'axios'
class IssuesStore {
#observable issues = []
constructor() {
autorun(() => console.log("Autorun:" + this.buildIssues))
reaction(
() => this.issues,
issues => console.log("Reaction: " + issues.join(", "))
)
}
getIssues(data) {
return data.map((issue) => ({title: issue.name, url: issue.url, labels: issue.labels}))
}
#computed get buildIssues() {
const authToken = 'token ' + process.env.REACT_APP_GH_OAUTH_TOKEN
axios.get(`https://api.github.com/repos/${process.env.REACT_APP_GH_USER}/gh-issues-app/issues`,
{ 'headers': {'Authorization': authToken} })
.then(response => {
console.log(response)
this.issues = this.getIssues(response.data)
return this.issues
})
.catch(function(response) {
console.log(response)
})
}
}
export default IssuesStore
In an attempt to separate API invocation promises from individual components and stores, I pulled out the axios call into a separate js file, as a collection of functions:
import axios from 'axios'
const authToken = 'token ' + process.env.REACT_APP_GH_OAUTH_TOKEN
export function loadIssues() {
return this.apiPromise(
`https://api.github.com/repos/${process.env.REACT_APP_GH_USER}/gh-issues-app/issues`,
{ 'headers': {'Authorization': authToken} }
)
}
export function apiPromise(endpoint, options) {
return axios.get(endpoint, options)
.then((response) => {
// console.log("response: " + JSON.stringify(response, null, 2))
return response.data.map((issue) => ({title: issue.name, url: issue.url, labels: issue.labels}))
})
.catch(function(response) {
console.log(response)
})
}
Now, my store looks like this:
import { observable, computed, autorun, reaction } from 'mobx'
import * as github from '../api/github'
class IssuesStore {
#observable issues = []
constructor() {
autorun(() => console.log("Autorun:" + this.buildIssues))
reaction(
() => this.issues,
issues => console.log("Reaction: " + issues.join(", "))
)
}
#computed get buildIssues() {
this.issues = github.loadIssues().data
return this.issues
}
}
export default IssuesStore
Much smaller... but the webpage now throws an error because it now sees the initial state of issues as undefined on first render.
Uncaught TypeError: Cannot read property 'map' of undefined
The promise completes successfully later on (as it should), but by then it's too late. Sure, I can set up a few null checks in my rendering components to not run .map or other such functions on empty or as-yet-undefined variables.
But why does the code work with no initial rendering errors before the refactoring, and not after? I thought the refactoring was effectively maintaining the same logic flow, but I must be missing something?
In your refactored version
github.loadIssues().data
Is always going to be undefined because the data property on that Promise will always be undefined.
In the original version, this.issues was only ever set once data returned from the api, so the only values that it was ever set to were the initial value [] and the filled array from the api response.
In yours, the three states are [] -> undefined -> and the filled array.
buildIssues should look something like this:
#computed get buildIssues() {
github.loadIssues().then((data) => {
this.issues = data
}).catch((err) => {
// handle err.
})
}

Categories