-
Notifications
You must be signed in to change notification settings - Fork 0
Exercise React Components State Props
//fetch library without backend? import fetchMock from 'fetch-mock'; import { getAll, getByType } from './data/pets'; import 'whatwg-fetch';
fetchMock.get('/api/pets', getAll()); fetchMock.get('/api/pets?type=cat', getByType('cat')); fetchMock.get('/api/pets?type=dog', getByType('dog')); fetchMock.get('/api/pets?type=micropig', getByType('micropig'));
export default fetchMock;
//index import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/App'; import './fetch-setup';
ReactDOM.render(, document.getElementById('root'));
[data](https://github.com/learn-co-students/react-props-and-state-lab-online-web-sp-000/blob/solution/src/data/pets.js)
//App import React from 'react';
import Filters from './Filters'; import PetBrowser from './PetBrowser';
class App extends React.Component { constructor() { super();
this.state = {
pets: [],
filters: {
type: 'all'
}
};
}
fetchPets = () => { let endpoint = '/api/pets';
if (this.state.filters.type !== 'all') {
endpoint += `?type=${this.state.filters.type}`;
}
fetch(endpoint)
.then(res => res.json())
.then(pets => this.setState({ pets: pets }));
};
onChangeType = ({ target: { value } }) => { this.setState({ filters: { ...this.state.filters, type: value } }); };
onAdoptPet = petId => { const pets = this.state.pets.map(p => { return p.id === petId ? { ...p, isAdopted: true } : p; }); this.setState({ pets: pets }); };
render() { return (
); } }export default App;
//Filters import React from 'react';
class Filters extends React.Component { render() { return (
<div className="field">
<button
onClick={this.props.onFindPetsClick}
className="ui secondary button">
Find pets
</button>
</div>
</div>
);
} }
export default Filters;
//PetBrowser import React from 'react';
import Pet from './Pet';
class PetBrowser extends React.Component { render() { const petCards = this.props.pets.map(pet => ( ));
return <div className="ui cards">{petCards}</div>;
} }
export default PetBrowser;
//Pet import React from 'react';
class Pet extends React.Component { render() { return (
Age: {this.props.pet.age}
Weight: {this.props.pet.weight}
export default Pet;
- Mounting -
static getDerivedStateFromProps(props, state)- Mounting -
componentDidMount()- Updating -
static getDerivedStateFromProps(props, state)- Updating -
shouldComponentUpdate(nextProps, nextState)- Updating -
render()- Updating -
getSnapshotBeforeUpdate(prevProps, prevState)- Updating -
componentDidUpdate(prevProps, prevState, snapshot)- Unmounting -
componentWillUnmount()- Element Ref