fetching json in seperate component - javascript

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.

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
}
}

My Vue.js Vuex store has 2 actions that make GET requests. The second action requires the response from the first one in order to work. How to do it?

I have 2 actions that make GET requests and save the response in the Vuex store. The first action getVersion() gets the most recent version of the game and that version is required in order to make the second GET request. Right now I've hard coded the version in the second action, however, my goal is to concatenate it inside the URL.
Sadly I'm not sure how to access it from inside the function. Console.log(state.version) returns null for some reason even though it shouldn't be. I call these functions from inside App.vue like this:
mounted(){
this.$store.dispatch('getVersion')
this.$store.dispatch('getChampions')
}
Vuex store
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
version: null,
champions: null
},
mutations: {
version(state, data){
state.version = data.version
},
champions(state, data){
state.champions = data.champions
}
},
actions: {
getVersion({commit}){
axios.get("http://ddragon.leagueoflegends.com/api/versions.json")
.then((response) => {
commit('version', {
version: response.data[0]
})
})
.catch(function (error) {
console.log(error);
})
},
getChampions({commit, state}){
axios.get("https://ddragon.leagueoflegends.com/cdn/9.24.1/data/en_US/champion.json")
.then((response) => {
commit('champions', {
champions: response.data.data
})
})
.catch(function (error) {
console.log(error);
})
}
},
getters: {
version: (state) => {
return state.version;
},
findChampion: (state) => (id) => {
let championId = id.toString();
let champion = Object.values(state.champions).find(value => value.key === championId);
return champion
}
}
})
With this part:
this.$store.dispatch('getVersion')
this.$store.dispatch('getChampions')
The second dispatch doesn't wait for the first one to finish. Meaning that it is firing before the first one has had a chance to finish getting the version.
You need to create a promise that should resolve before the second dispatch is called.
You could try doing it this way:
async mounted(){
await this.$store.dispatch('getVersion')
await this.$store.dispatch('getChampions')
}
or if you don't want to use async/await
this.$store.dispatch('getVersion').then(() => {
this.$store.dispatch('getChampions');
});
And in the action you should add return to the request (this is important):
return axios.get(...
dispatcher returns a promise
this.$store.dispatch('getVersion').then(()=>{
this.$store.dispatch('getChampions');
});

Why am I getting 2 times data null and data?

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.)

Function inside component not receiving latest version of Redux-state to quit polling

I have an issue where I am trying to use the Redux state to halt the execution of some polling by using the state in an if conditional. I have gone through posts of SO and blogs but none deal with my issue, unfortunately. I have checked that I am using mapStateToProps correctly, I update state immutably, and I am using Redux-Thunk for async actions. Some posts I have looked at are:
Component not receiving new props
React componentDidUpdate not receiving latest props
Redux store updates successfully, but component's mapStateToProps receiving old state
I was kindly helped with the polling methodology in this post:Incorporating async actions, promise.then() and recursive setTimeout whilst avoiding "deferred antipattern" but I wanted to use the redux-state as a single source of truth, but perhaps this is not possible in my use-case.
I have trimmed down the code for readability of the actual issue to only include relevant aspects as I have a large amount of code. I am happy to post it all but wanted to keep the question as lean as possible.
Loader.js
import { connect } from 'react-redux';
import { delay } from '../../shared/utility'
import * as actions from '../../store/actions/index';
const Loader = (props) => {
const pollDatabase = (jobId, pollFunction) => {
return delay(5000)
.then(pollFunction(jobId))
.catch(err => console.log("Failed in pollDatabase function. Error: ", err))
};
const pollUntilComplete = (jobId, pollFunction) => {
return pollDatabase(jobId, pollFunction)
.then(res => {
console.log(props.loadJobCompletionStatus) // <- always null
if (!props.loadJobCompletionStatus) { <-- This is always null which is the initial state in reducer
return pollUntilComplete(jobId, pollFunction);
}
})
.catch(err=>console.log("Failed in pollUntilComplete. Error: ", err));
};
const uploadHandler = () => {
...
const transferPromise = apiCall1() // Names changed to reduce code
.then(res=> {
return axios.post(api2url, res.data.id);
})
.then(postResponse=> {
return axios.put(api3url, file)
.then(()=>{
return instance.post(api3url, postResponse.data)
})
})
transferDataPromise.then((res) => {
return pollUntilComplete(res.data.job_id,
props.checkLoadTaskStatus)
})
.then(res => console.log("Task complete: ", res))
.catch(err => console.log("An error occurred: ", err))
}
return ( ...); //
const mapStateToProps = state => {
return {
datasets: state.datasets,
loadJobCompletionStatus: state.loadJobCompletionStatus,
loadJobErrorStatus: state.loadJobErrorStatus,
loadJobIsPolling: state.loadJobPollingFirestore
}
}
const mapDispatchToProps = dispatch => {
return {
checkLoadTaskStatus: (jobId) =>
dispatch(actions.loadTaskStatusInit(jobId))
};
};
export default connect(mapStateToProps, mapDispatchToProps)(DataLoader);
delay.js
export const delay = (millis) => {
return new Promise((resolve) => setTimeout(resolve, millis));
}
actions.js
...
export const loadTaskStatusInit = (jobId) => {
return dispatch => {
dispatch(loadTaskStatusStart()); //
const docRef = firestore.collection('coll').doc(jobId)
return docRef.get()
.then(jobData=>{
const completionStatus = jobData.data().complete;
const errorStatus = jobData.data().error;
dispatch(loadTaskStatusSuccess(completionStatus, errorStatus))
},
error => {
dispatch(loadTaskStatusFail(error));
})
};
}
It seems that when I console log the value of props.loadJobCompletionStatus is always null, which is the initial state of in my reducer. Using Redux-dev tools I see that the state does indeed update and all actions take place as I expected.
I initially had placed the props.loadJobCompletionStatus as an argument to pollDatabase and thought I had perhaps created a closure, and so I removed the arguments in the function definition so that the function would fetch the results from the "upper" levels of scope, hoping it would fetch the latest Redux state. I am unsure as to why I am left with a stale version of the state. This causes my if statement to always execute and thus I have infinite polling of the database.
Can anybody point out what might be causing this?
Thanks
I'm pretty sure this is because you are defining a closure in a function component, and thus the closure is capturing a reference to the existing props at the time the closure was defined. See Dan Abramov's extensive post "The Complete Guide to useEffect" to better understand how closures and function components relate to each other.
As alternatives, you could move the polling logic out of the component and execute it in a thunk (where it has access to getState()), or use the useRef() hook to have a mutable value that could be accessed over time (and potentially use a useEffect() to store the latest props value in that ref after each re-render). There are probably existing hooks available that would do something similar to that useRef() approach as well.

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