import React from 'react'; export default class App extends React.Component { state = { users: [], status: 'initial', }; componentDidMount() { this.getUsers(); this.myCoolFunction('first', 'second', (result) => console.log('yay the result is', result)); this.myCoolFunction('first', 'second'); } myCoolFunction = ( param1, param2, callback = () => console.log("function is not passed") ) => { let result = 'do stuff with ' + param1 + ' ' + param2; console.log(callback) console.log('just before callback(result)'); callback(result); }; getUsers = async (id) => { setTimeout(() => { this.setState({ status: 'searching', users: [], }); }, 3000); setTimeout(() => { this.setState( { status: 'done', users: [ { id: 23, name: 'gdfgd' }, { id: 24, name: 'weqweeq' } ], }, () => this.state.users.map((user) => console.log(user.name)) ); }, 5000); }; render() { if (this.state.status === 'initial') { return <div>ini</div>; } if (this.state.status === 'searching') { return <div>searching</div>; } if (this.state.status === 'done') { return ( <ul> {this.state.users.map((user) => ( <li key={user.id}>{user.name}</li> ))} </ul> ); } } }
Friday, January 21, 2022
React callback
Passing function as argument and callback in setState.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment