json - ReactJS - Array comparison, Render only if name exists in both arrays -
i working on star wars web app using reactjs data being pulled swapi (api returning json data star wars). have working more control on results pulled. every character being pulled swapi, specify characters displayed in own json file , compare results swapi.
here breakdown of tasks:
use fetch pull star wars character information json swapi , apiresonse.props.results
add array of specified characters app state.characters
compare names app.state.characters apiresponse.results , render list of characters
here current code:
/* app */ class app extends react.component { // set initial state constructor() { super(); this.state = { characters: [], } } // add specified characters app.state.characters componentdidmount() { this.setstate ({ characters : require('./charnames') }); } render() { return ( <div> <navbar/> <header/> <characters/> <footer/> </div> ); } }
swapi component
// uses react-fetch retrive json swapi class api extends react.component{ render(){ return ( <fetch url="http://swapi.co/api/people/"> <apiresponse test={this.props.results}/> </fetch> ) } } class apiresponse extends react.component{ render(){ if (this.props.results) { return ( {/* believe array comparison should occur here */} <div classname="row"> {this.props.results.map((key) => <h1>{key.name}</h1> )} </div> ) } } }
app state
props empty state characters: array[2] 0: {name: "luke skywalker"} 1: {name: "han solo"}
api props
props results: array[10] 0: {gender: "male", name="luke skywalker"} 1: {gender: "male", name="han solo"} 2: {gender: "female", name="leia organa"}
so results above "lei organa" omitted not exist in app state, hope question makes sense!
tl;dr - compare 'names' app.state.characters apiresponse.props.results
you have correct idea, want run filter
method against api results matches against application state.
i highly recommend attempting write basic filter yourself, excellent tutorial can found here:
http://adripofjavascript.com/blog/drips/filtering-arrays-with-array-filter.html
once have done leveraging lodash's _.filter
method (https://lodash.com/docs#filter) job done , easily.
one last note, filtering in render method of apiresponse
, consider leveraging componentwillreceiveprops
, doing filter there, leave render dumb possible.
Comments
Post a Comment