'Lifecycle of Reactive Effects'·续4
label { display: block; margin-bottom: 10px; }
In this version, the App component passes a boolean prop instead of a function. Inside the Effect, you decide which function to use. Since both createEncryptedConnection and createUnencryptedConnection are declared outside the component, they aren't reactive, and don't need to be dependencies. You'll learn more about this in Removing Effect Dependencies.
Populate a chain of select boxes
In this example, there are two select boxes. One select box lets the user pick a planet. Another select box lets the user pick a place on that planet. The second box doesn't work yet. Your task is to make it show the places on the chosen planet.
Look at how the first select box works. It populates the planetList state with the result from the "/planets" API call. The currently selected planet's ID is kept in the planetId state variable. You need to find where to add some additional code so that the placeList state variable is populated with the result of the "/planets/" + planetId + "/places" API call.
If you implement this right, selecting a planet should populate the place list. Changing a planet should change the place list.
If you have two independent synchronization processes, you need to write two separate Effects.
```js src/App.js import { useState, useEffect } from 'react'; import { fetchData } from './api.js';
export default function Page() { const [planetList, setPlanetList] = useState([]) const [planetId, setPlanetId] = useState('');
const [placeList, setPlaceList] = useState([]); const [placeId, setPlaceId] = useState('');
useEffect(() => { let ignore = false; fetchData('/planets').then(result => { if (!ignore) { console.log('Fetched a list of planets.'); setPlanetList(result); setPlanetId(result[0].id); // Select the first planet } }); return () => { ignore = true; } }, []);
return ( <>
You are going to: {placeId || '???'} on {planetId || '???'}
</> ); }
```js src/api.js hidden
export function fetchData(url) {
if (url === '/planets') {
return fetchPlanets();
} else if (url.startsWith('/planets/')) {
const match = url.match(/^\/planets\/([\w-]+)\/places(\/)?$/);
if (!match || !match[1] || !match[1].length) {
throw Error('Expected URL like "/planets/earth/places". Received: "' + url + '".');
}
return fetchPlaces(match[1]);
} else throw Error('Expected URL like "/planets" or "/planets/earth/places". Received: "' + url + '".');
}
async function fetchPlanets() {
return new Promise(resolve => {
setTimeout(() => {
resolve([{
id: 'earth',
name: 'Earth'
}, {
id: 'venus',
name: 'Venus'
}, {
id: 'mars',
name: 'Mars'
}]);
}, 1000);
});
}
async function fetchPlaces(planetId) {
if (typeof planetId !== 'string') {
throw Error(
'fetchPlaces(planetId) expects a string argument. ' +
'Instead received: ' + planetId + '.'
);
}
return new Promise(resolve => {
setTimeout(() => {
if (planetId === 'earth') {
resolve([{
id: 'laos',
name: 'Laos'
}, {
id: 'spain',
name: 'Spain'
}, {
id: 'vietnam',
name: 'Vietnam'
}]);
} else if (planetId === 'venus') {
resolve([{
id: 'aurelia',
name: 'Aurelia'
}, {
id: 'diana-chasma',
name: 'Diana Chasma'
}, {
id: 'kumsong-vallis',
name: 'Kŭmsŏng Vallis'
}]);
} else if (planetId === 'mars') {
resolve([{
id: 'aluminum-city',
name: 'Aluminum City'
}, {
id: 'new-new-york',
name: 'New New York'
}, {
id: 'vishniac',
name: 'Vishniac'
}]);
} else throw Error('Unknown planet ID: ' + planetId);
}, 1000);
});
}
label { display: block; margin-bottom: 10px; }
There are two independent synchronization processes:
- The first select box is synchronized to the remote list of planets.
- The second select box is synchronized to the remote list of places for the current
planetId.
This is why it makes sense to describe them as two separate Effects. Here's an example of how you could do this:
```js src/App.js import { useState, useEffect } from 'react'; import { fetchData } from './api.js';
export default function Page() { const [planetList, setPlanetList] = useState([]) const [planetId, setPlanetId] = useState('');
const [placeList, setPlaceList] = useState([]); const [placeId, setPlaceId] = useState('');
useEffect(() => { let ignore = false; fetchData('/planets').then(result => { if (!ignore) { console.log('Fetched a list of planets.'); setPlanetList(result); setPlanetId(result[0].id); // Select the first planet } }); return () => { ignore = true; } }, []);
useEffect(() => { if (planetId === '') { // Nothing is selected in the first box yet return; }
let ignore = false; fetchData('/planets/' + planetId + '/places').then(result => { if (!ignore) { console.log('Fetched a list of places on "' + planetId + '".'); setPlaceList(result); setPlaceId(result[0].id); // Select the first place } }); return () => { ignore = true; } }, [planetId]);
return ( <>
You are going to: {placeId || '???'} on {planetId || '???'}
</> ); }
```js src/api.js hidden
export function fetchData(url) {
if (url === '/planets') {
return fetchPlanets();
} else if (url.startsWith('/planets/')) {
const match = url.match(/^\/planets\/([\w-]+)\/places(\/)?$/);
if (!match || !match[1] || !match[1].length) {
throw Error('Expected URL like "/planets/earth/places". Received: "' + url + '".');
}
return fetchPlaces(match[1]);
} else throw Error('Expected URL like "/planets" or "/planets/earth/places". Received: "' + url + '".');
}
async function fetchPlanets() {
return new Promise(resolve => {
setTimeout(() => {
resolve([{
id: 'earth',
name: 'Earth'
}, {
id: 'venus',
name: 'Venus'
}, {
id: 'mars',
name: 'Mars'
}]);
}, 1000);
});
}
async function fetchPlaces(planetId) {
if (typeof planetId !== 'string') {
throw Error(
'fetchPlaces(planetId) expects a string argument. ' +
'Instead received: ' + planetId + '.'
);
}
return new Promise(resolve => {
setTimeout(() => {
if (planetId === 'earth') {
resolve([{
id: 'laos',
name: 'Laos'
}, {
id: 'spain',
name: 'Spain'
}, {
id: 'vietnam',
name: 'Vietnam'
}]);
} else if (planetId === 'venus') {
resolve([{
id: 'aurelia',
name: 'Aurelia'
}, {
id: 'diana-chasma',
name: 'Diana Chasma'
}, {
id: 'kumsong-vallis',
name: 'Kŭmsŏng Vallis'
}]);
} else if (planetId === 'mars') {
resolve([{
id: 'aluminum-city',
name: 'Aluminum City'
}, {
id: 'new-new-york',
name: 'New New York'
}, {
id: 'vishniac',
name: 'Vishniac'
}]);
} else throw Error('Unknown planet ID: ' + planetId);
}, 1000);
});
}
label { display: block; margin-bottom: 10px; }
This code is a bit repetitive. However, that's not a good reason to combine it into a single Effect! If you did this, you'd have to combine both Effect's dependencies into one list, and then changing the planet would refetch the list of all planets. Effects are not a tool for code reuse.
Instead, to reduce repetition, you can extract some logic into a custom Hook like useSelectOptions below:
```js src/App.js import { useState } from 'react'; import { useSelectOptions } from './useSelectOptions.js';
export default function Page() { const [ planetList, planetId, setPlanetId ] = useSelectOptions('/planets');
const [
placeList,
placeId,
setPlaceId
] = useSelectOptions(planetId ? /planets/${planetId}/places : null);
return ( <>
You are going to: {placeId || '...'} on {planetId || '...'}
</> ); }
```js src/useSelectOptions.js
import { useState, useEffect } from 'react';
import { fetchData } from './api.js';
export function useSelectOptions(url) {
const [list, setList] = useState(null);
const [selectedId, setSelectedId] = useState('');
useEffect(() => {
if (url === null) {
return;
}
let ignore = false;
fetchData(url).then(result => {
if (!ignore) {
setList(result);
setSelectedId(result[0].id);
}
});
return () => {
ignore = true;
}
}, [url]);
return [list, selectedId, setSelectedId];
}
```js src/api.js hidden export function fetchData(url) { if (url === '/planets') { return fetchPlanets(); } else if (url.startsWith('/planets/')) { const match = url.match(/^\/planets\/([\w-]+)\/places(\/)?$/); if (!match || !match[1] || !match[1].length) { throw Error('Expected URL like "/planets/earth/places". Received: "' + url + '".'); } return fetchPlaces(match[1]); } else throw Error('Expected URL like "/planets" or "/planets/earth/places". Received: "' + url + '".'); }
async function fetchPlanets() { return new Promise(resolve => { setTimeout(() => { resolve([{ id: 'earth', name: 'Earth' }, { id: 'venus', name: 'Venus' }, { id: 'mars', name: 'Mars' }]); }, 1000); }); }
async function fetchPlaces(planetId) { if (typeof planetId !== 'string') { throw Error( 'fetchPlaces(planetId) expects a string argument. ' + 'Instead received: ' + planetId + '.' ); } return new Promise(resolve => { setTimeout(() => { if (planetId === 'earth') { resolve([{ id: 'laos', name: 'Laos' }, { id: 'spain', name: 'Spain' }, { id: 'vietnam', name: 'Vietnam' }]); } else if (planetId === 'venus') { resolve([{ id: 'aurelia', name: 'Aurelia' }, { id: 'diana-chasma', name: 'Diana Chasma' }, { id: 'kumsong-vallis', name: 'Kŭmsŏng Vallis' }]); } else if (planetId === 'mars') { resolve([{ id: 'aluminum-city', name: 'Aluminum City' }, { id: 'new-new-york', name: 'New New York' }, { id: 'vishniac', name: 'Vishniac' }]); } else throw Error('Unknown planet ID: ' + planetId); }, 1000); }); }
```css
label { display: block; margin-bottom: 10px; }
Check the useSelectOptions.js tab in the sandbox to see how it works. Ideally, most Effects in your application should eventually be replaced by custom Hooks, whether written by you or by the community. Custom Hooks hide the synchronization logic, so the calling component doesn't know about the Effect. As you keep working on your app, you'll develop a palette of Hooks to choose from, and eventually you won't need to write Effects in your components very often.
