Skip to content

Instantly share code, notes, and snippets.

@plmok61
Last active April 11, 2019 15:36
Show Gist options
  • Save plmok61/8d03ad89d244403bfd9ca65344bbf451 to your computer and use it in GitHub Desktop.
Save plmok61/8d03ad89d244403bfd9ca65344bbf451 to your computer and use it in GitHub Desktop.
// solution 1
lampExists(lamp){
if(lamp.toLowerCase().includes(this.state.query.toLowerCase())) {
return true
} else {
return AsyncStorage.getItem(lamp).then(value=> {
if(value !== null && value
.toLowerCase()
.includes(this.state.query.toLowerCase())) {
return true;
}
return false;
}).catch(err=>alert(err));
}
}
// solution 2
async lampExists(lamp){
let myBool;
if(lamp.toLowerCase().includes(this.state.query.toLowerCase())) {
return true
} else {
const value = await AsyncStorage.getItem(lamp);
if(value !== null && value
.toLowerCase()
.includes(this.state.query.toLowerCase())) {
return true;
}
return false;
}
}
// Update
class YourComponent extends React.Component {
constructor(props) {
this.state = {
lamps: [],
loading: false,
}
this.fetchLamps = this.fetchLamps.bind(this);
}
componentDidMount() {
this.getLamps()
}
asycn getLamps() {
// set loading state to true
this.setState({ loading: true });
// Do async work here
const lamps = await // fetch your lamps
// probably some error handling logic here
// set lamps to state and set loading state to false
this.setState({
lamps: lamps,
loading: false,
});
}
render() {
if (this.state.loading) {
return <Text>Loading</Tex>;
}
return (
<View>
{
this.state.lamps.map(lamp => (
<LampsList
key={lamp}
lamp={lamp}
navigation={this.props.navigation}
/>
)
}
</View>
);
}
}
@fanatic75
Copy link

Both solutions returns a promise instead of boolean.
Cannot extract boolean by using .then function in render function of React as it doesn't allow me.
Posting my render function code as well, so you can get a better idea.
{this.state.lamps.map(lamp => { if (this.state.query === "") { return <LampsList key={lamp} lamp={lamp} navigation={this.props.navigation} /> } else { return (this.lampExists(lamp)?<LampsList key={lamp} lamp={lamp} navigation={this.props.navigation} />:null) } })}

@fanatic75
Copy link

fanatic75 commented Apr 11, 2019

{this.state.lamps.map(lamp => { if (this.state.query === "") { return <LampsList key={lamp} lamp={lamp} navigation={this.props.navigation} /> } else { this.lampExists(lamp) .then(result=>{ if(result===true){ return <LampsList key={lamp} lamp={lamp} navigation={this.props.navigation} /> }else{ return null } }) .catch(err=>alert(err)); } })}
If I change my render function to this, it still doesn't work, because the component is again not getting returned and only a promise is getting returned which won't display my component.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment