ReactJS - REST API query inside .map function? - javascript

How do I generate repetitive mark-up elements in a React component, that also require a REST API query for each of them? Initially I had the calls completing in a for-each loop within the componentDidMount function. But that required calling setState inside the loop, in order to trigger a re-Render. The behavior was unstable, and apparently that technique is not a good idea.
So, now I'm trying to get the queries to run inside the .map function of my render (see below). But that's producing this error.
Is there a way to return the element value instead of a promise? (Probably more of a JS question than a React one...)
Or am I going about this the wrong way altogether?
return (<div>
{this.props.currentProject.Tasks.map((task => {
return ProjectsService.getTaskBaselines(this.props.currentProject.PWAGuid, task.TaskId, this.props.context).then((baseline: any): any => {
return (<div>{task.TaskName}</div>);
})
}))}
</div>);

It seems like you want to query all APIs and then handle the response once all are settled.
Try this:
const promises = this.props.currentProject.Tasks.map((task => {
return new Promise(function(resolve, reject) {
resolve(task);
});
Promise.all(promises).then((data) => {
this.setState({
// act on all of your data
});
});
Then render this.state in your render() function.

Related

Having promise response inside Vue template interpolation

I'm using Vue 2 and the composition API. My current component receives a prop from a parent and I render different data based on it, on the screen - the prop is called "result" and is of type Object, containing multiple info. I receive one "result" at a time, but multiple will be rendered - you can think of my "result" as a google search result - which means that the page will have multiple results.
The issue I have is that for one of the info inside "result", I need to call an asynchronous method and display its result, which is what I cannot accomplish.
Currently this is what I have:
<div>
{{ getBoardName(props.result.boardReference) }}
</div>
Method inside the script:
async function getBoardName(boardReference) {
var result = await entriesApi.getBoardName({
boardReference: boardReference,
});
return result;
}
It displays "[object Promise]", although if I console.log(result) right before returning it, it's just what I need, so it seems to me as if the interpolation doesn't actually wait for the promise result.
I've also tried using "then" inside the interpolation:
{{
getBoardName(props.result.boardReference).then((value) => {
return value;
})
}}
I was thinking about using a computed property but I am not sure how that would work, as the response I need from the method has to be connected to each result individually.
Please ask for further clarifications if needed.
As you thought, the interpolation does not actually wait for the result so this is why you have a Promise object.
Since you are using the composition API, what you can actually do is to use a reactive state (using the ref() function if you are waiting for a primitive type, which seems to be the case here, or the reactive() function for objects) and update the state within the onMounted() lifecycle hook.
setup(props, context) {
const boardGameName = ref("");
onMounted(async () => {
boardGameName.value = await getBoardName(props.result.boardReference);
});
async function getBoardName(boardReference) {
var result = await entriesApi.getBoardName({
boardReference: boardReference,
});
return result;
}
return {
boardGameName,
};
}
Since you are dealing with async data, you could add a loading state so you can show a spinner or something else until the data is available.
If your board reference changes over time, you could use a watcher to update your board game name.
Good luck with your project!

Best practise to handle with responses and incoming props

with redux, we uses actions to handle with crud operations. But I stuck at some points. If we send async requests inside of component. We can easly handle with response. But when we send request through actions, we dont know what happened. Is request send successfully ? it took how much amount of time ? What kind of response is returned ? we don't know that
I will clarify question with samples..
lets update a post.
onClick () {
postsApi.post(this.state.post) | we know how much time
.then(res => res.data) | has took to execute
.then(res => { | request
console.log(res) // we have the response
})
.catch(err => console.log(error))
}
But if we use actions
onClick () {
this.props.updatePost(this.state.post) // we know nothing what will happen
}
or handling with incoming props. lets say I have fetchPost() action to retrieve post
componentDidMount(){
this.props.fetchPost()
}
render method and componentDidUpdate will run as well. It's cool. But what if I want to update my state by incoming props ? I can't do this operation inside of componentDidUpdate method. it causes infinity loop.
If I use componentWillUpdate method, well, things works fine but I'm getting this warning.
Warning: componentWillReceiveProps has been renamed, and is not
recommended for use. Move data fetching code or side effects to
componentDidUpdate. If you're updating state whenever props change,
refactor your code to use memoization techniques or move it to static
getDerivedStateFromProps
I can't use componentDidUpdate method for infinty loop. Neither getDerivedStateFromProps method because it's run everytime when state change.
Should I continue to use componentWillMethod ? Otherwise what should I use and why (why componentWillMethod is unsafe ?)
If I understand correcty, what you would like to do is to safely change your local state only when your e.g. updatePost was successful.
If indeed that is your case, you can pass a callback function on your updatePost and call this as long as your update was succefull.
successfulUpdate() {
// do your thing
this.setState( ... );
}
onClick () {
this.props.updatePost(this.state.post, this.successfulUpdate) // we know nothing what will happen
}
UPDATE:
You can also keep in mind that if your action returns a promise, then you can just use the then method:
onClick () {
this.props.updatePost(this.state.post).then(this.onFulfilled, this.onRejected)
}
I think we can use redux-thunk in this cases. What if we dispatch an async function instead of dispatch an action object?
"Neither getDerivedStateFromProps method because it's run everytime when state change." - does it matter? You can avoid setting state with every getDerivedStateFromProps call by using a simple condition inside.
Example:
static getDerivedStateFromProps(props, state) {
if (props.post !== state.post) { // or anything else
return {
post: props.post,
};
}
return null;
};
An infinite loop will not occur.
Here is my way for such cases. We can redux-thunk for asynchronous calls such as api call. What if we define the action that returns promise? Please check the code below.
actions.js
export const GetTodoList = dispatch => {
return Axios.get('SOME_URL').then(res => {
// dispatch some actions
// return result
return res.data;
});
}
TodoList.js
onClick = async () => {
const { GetTodoList } = this.props;
try {
const data = await GetTodoList();
// handler for success
this.setState({
success: true,
data
});
} catch {
// handler for failure
this.setState({
success: fail,
data: null
});
}
}
const mapStateToProps = state => ({
GetTodoList
});
So we can use actions like API(which returns promise) thanks to redux-thunk.
Let me know your opinion.

React - Promise - "this" is undefined

I'm sure this is a beginner question, but actually I can't figure out, why this is undefined.
But let's start from the beginning. I'm using react with react-redux to load data. In this special case I first want to load all positions of a project and then load the verfication files. That are 2 queries, so I want to be sure, that the positions are loaded completely before start loading the verifications. So I thought - oohh, let's use a promise here.
It starts with the method loadVerifications(event). In this method, the method loadProjectPositions(event) is being called. I can see that the project positions are loaded correctly.
When the positions are loaded it should load then the verification files (.then(()...).
Actually in this .then() method, this is undefined, but why?
class Kundenkommunikation extends Component {
constructor(p) {
super(p);
this.state = {
};
this.loadProjectPositions = this.loadProjectPositions.bind(this);
this.loadVerifications = this.loadVerifications.bind(this);
}
loadProjectPositions(event) {
return new Promise((resolve,reject) => {
this.props.getProjektPositionenByProjektIdForModulId(13, event.value);
resolve(this)
})
}
loadVerifications(event) {
this.loadProjectPositions(event)
.then(() => {
this.props.projektpositionen && Object.values(this.props.projektpositionen).map((position) => {
if(position.nachweis != null) {
this.props.createBericht(position.nachweis.id,'SherpaVerbinder');
}
});
})
}
UPDATE:
Even when I'm bind loadVerifications in the constructor, it doesn't work. this stays undefined.
You should use bind(this) method for loadVerifications to get a component's context from the external function or
Another is arrow functions loadVerifications= (event) => {...}
Ok, thanks for all hints and tipps. Lately it turned out, that Chrome did not show the data for whatever reason, but the data was available. I could find out by simply add an console.log(this.props) into the code, then it showed me all props and I was able to see that this is not undefined.
But the real issue was then, that the data was not loaded at this time. So I needed to add a then into the method loadProjectPositions to be sure, that the data is returned before resolving the Promise.
loadProjectPositions(event) {
return new Promise((resolve,reject) => {
this.props.getProjektPositionenByProjektIdForModulId(13, event.value)
.then(() => {
resolve(this)
});
})
}
After adding this, all data was loaded correctly at that time and then all worked.

ReactJS: multiple setStates happening asynchronously, state not updated

Facing an issue where state is not updated, before function (filterAndSort) located in render is fired. I have added a console.log statement within the function, and only one of the states gets updated. My code seems logical to me, as I have set an if condition where function is fired only after setState occurs
Full error message:
Warning: Can't call setState (or forceUpdate) on an unmounted
component. This is a no-op, but it indicates a memory leak in your
application. To fix, cancel all subscriptions and asynchronous tasks
in the componentWillUnmount method.
However, i'm suspecting that because i'm having multiple setStates happening asynchronously.
I'm thinking that perhaps, i need to re-write the componendDidMount to setState for all variables only after all axios requests are fetched.
Multiple Axios Requests Into ReactJS State
Another solution I think would be to having the returned results of the function stored as a state instead of a variable, then add a componentDidUpdate.
componentDidUpdate(prevProps, prevState) {
if (this.state.value > prevState.value) {
this.filterAndSort();
}
}
Component
class Results extends Component {
constructor(){
super()
this.state = {
results: [],
races: [],
arr = []
isLoading: true
};
}
componentDidMount(){
const oneRequest = axios.get(URL_ONE)
.then(response =>
response.data.data.map(result => ({...
))
)
.then(results => this.setState({results, isLoading: false}))
const twoRequest = axios.get(URL_TWO)
.then(response =>
response.data.data.map(race => ({...}))
)
.then(races => this.setDefault(races))
}
setDefault = (races) => {
........
this.setState({arr, races, isLoading:false})
}
filterAndSort = (races, results) => {
console.log(races, results)
.......
}
render() {
const{races, results} = this.state
if (isLoading == true) {
return (
<div>
<p>Loading...</p>
</div>
)
} else {
return (
<div>
<BarChart
qualData={this.filterAndSort(races, results)}
raceData={this.filterAndSort(races, results)}
width="1200"
height="500" />
</div>
);
}
}
}
export default Results;
Well, there are a number of things that come to my mind.
First, you set the isLoading to false only when you have one of two pieces of data, whichever comes first, thus the render method will at some point call your function with either empty races or results.
Another thing, you are asynchronously calling setState. By the time the request is finished your component may not exist any more thus it will try to update a non existing component and fail with that error.
For the first issue, one possible solution is to have two isLoading-variables for both results and races.
For the second issue (setState called on an unmountedComponent), its a bit more complicated, because you need to somehow cancel the request. I recommend reading more on this, the general advice is to move your data out of the components using a library like redux. If you google cancel promise on unmount you will find discussion on this. You can also deal with it using an "isMounted" variable, which will work as an ugly patch.
So, as soon as request one (or two) is completed, setState is called, the component is then re-rendered. The isLoading is now true so filterAndSort is called with results (or races) but not both because the second request is still pending.
Finally, in your render method your isLoading needs to be first defined (i assume its ok in your code but not in the question) and the is True comparison can be better put as
if (isLoading) { instead of if (isLoading == True) {
You're right. When making multiple requests its always best practice to wait for them all to resolve before moving forward. For that you can use the Promise library which is built into ES6. Also, for fetching of data its best practice, so far as i've seen, to do it in componentWillMount(). I'll also add that the context of this changes when inside an async function. So in your componentWillMount():
let promiseArr = [axios.get(URL_ONE), axios.get(URL_TWO)];
let _this = this;
Promise.all(promiseArr)
.then((resp) => {
// Call _this.setState() here. Response from URL_ONE
// will be available in resp.data[0] and URL_TWO in resp.data[1]
}).catch((err) => {
console.log(err);
})
Also, in your constructor:
constructor(){
super()
this.state = {
results: [],
races: [],
arr = []
isLoading: true
};
this.setDefault = this.setDefault.bind(this);
this.filterAndSort = this.filterAndSort.bind(this);
}
Using .bind to make sure that the context of this is referrering to the current instance of the class when calling those methods.
I think after doing those things that error will go away. Hope that helps.

Testing fetch() method inside React component

I have an App component that is responsible for rendering child input components, it is also responsible for handling fetch requests to the Twitch API via a method called channelSearch. I have tried to adhere to suggested best practices outlined here for working with ajax/fetch with React.
The method is passed down through props and called via a callback.
Note the fetch method is actually isomorphic-fetch.
channelSearch (searchReq, baseUrl="https://api.twitch.tv/kraken/channels/") {
fetch(baseUrl + searchReq)
.then(response => {
return response.json();
})
.then(json => {
this.setState({newChannel:json});
})
.then( () => {
if (!("error" in this.state.newChannel) && this.channelChecker(this.state.newChannel._id, this.state.channelList) ) {
this.setState(
{channelList: this.state.channelList.concat([this.state.newChannel])}
);
}
})
.catch(error => {
return error;
});
}
I am currently trying to write a test for the channelSearch method. I am currently using enzyme and jsdom to mount the entire <App> component in a DOM. Find the child node with the callback, simulate a click (which should fire the callback) and check to see if the state of the component has been changed. However, this does not seem to work.
I have also tried calling the method directly, however, I run into problems with this.state being undefined.
test('channel search method should change newChannel state', t => {
const wrapper = mount(React.createElement(App));
wrapper.find('input').get(0).value = "test";
console.log(wrapper.find('input').get(0).value);
wrapper.find('input').simulate("change");
wrapper.find('button').simulate("click");
console.log(wrapper.state(["newChannel"]));
});
I am really lost, I am not sure if the method itself is poorly written or I am not using the correct tools for the job. Any guidance will be greatly appreciated.
Update #1:
I included nock as recommended in comments, test now looks like this:
test('channel search method should change newChannel state', t => {
// Test object setup
var twitch = nock('https://api.twitch.tv')
.log(console.log)
.get('/kraken/channels/test')
.reply(200, {
_id: '001',
name: 'test',
game: 'testGame'
});
function checker() {
if(twitch.isDone()) {
console.log("Done!");
console.log(wrapper.state(["newChannel"]));
}
else {
checker();
}
}
const wrapper = mount(React.createElement(App));
wrapper.find('input').get(0).value = "test";
wrapper.find('input').simulate("change");
wrapper.find('button').simulate("click");
checker();
});
This still does not seem to change the state of the component.
fetch is asynchronous but you're testing synchronously, you need to either mock fetch with a synchronous mock or make the test asynchronous.
nock may work for you here.
I suggest you create a sample of your test using plnkr.
I agree with Tom that you're testing synchronously. It would of course be helpful to show off your actual component code (all of the relevant portions, like what calls channelSearch, or at the least describe it by saying e.g. "channelSearch is called by componentDidMount()". You said:
I run into problems with this.state being undefined.
This is because this.setState() is asynchronous. This is for performance reasons, so that React can batch changes.
I suspect you'll need to change your code that is currently:
.then(json => {
this.setState({newChannel:json});
})
to:
.then(json => {
return new Promise(function(resolve, reject) {
this.setState({newChannel:json}, resolve);
})
})
Note that your checker() method won't work. It's looping, but twitch.isDone() will never be true because it never has a chance to run. Javascript is single threaded, so your checker code will run continuously, not allowing anything else in between.
If you set up the plnkr, I'll take a look.
Refactor out the fetch code from the component then pass it it to the component as a callback function in the properties.
export class Channel extends React.Component {
componentDidMount() {
this.props.searchFunction().then(data => this.setState(data));
}
render() {
return <div>{this.state}</div>;
}
}
Uage:
function channelSearch(name) {
return fetch(`https://api.twitch.tv/kraken/search/channels?query=${name}`);
}
<Channel searchFunction={channelSearch} />
Now you can test the API functionality independently of the component.

Categories

Resources