I'm trying to search the names of past SpaceX launches and it's not working. I'm sourcing from the SpaceX launches API using Axios: https://api.spacexdata.com/v4/launches/past
When I try to search all that happens is that the api request is refreshed but with the same initial results, not with that is typed in the text input.
App.js:
function App() {
const [params, setParams] = useState({});
const {launches, loading, error} = FetchLaunches(params);
const handleParamChange = (e) => {
const param = e.target.name;
const value = e.target.value;
setParams(prevParams => {
return { ...prevParams, [param]: value }
});
}
return (
<main className='app'>
<SearchForm params={params} onParamChange={handleParamChange}/>
<div className="launch-list">
{loading && <h2>Loading...</h2>}
{error && <h2>An error occured</h2>}
{launches.map(launch => {
return <LaunchItem
launch={launch}
key={launch.flight_number}
/>
})}
</div>
</main>
);
}
fetch-launches.js: gets data using the axios library:
const ACTIONS = {
MAKE_REQUEST: 'make-request',
GET_DATA: 'get-data',
ERROR: 'error',
};
const SPACEX_URL = 'https://api.spacexdata.com/v4/launches/past';
const reducer = (state, action) => {
switch (action.type) {
case ACTIONS.MAKE_REQUEST:
return { loading: true, launches: [] };
case ACTIONS.GET_DATA:
return { ...state, loading: false, launches: action.payload.launches };
case ACTIONS.ERROR:
return {
...state,
loading: false,
error: action.payload.error,
launches: [],
};
default:
return state;
}
};
const FetchLaunches = (params) => {
const [state, dispatch] = useReducer(reducer, {
launches: [],
loading: true,
});
useEffect(() => {
const cancelToken1 = axios.CancelToken.source();
dispatch({ type: ACTIONS.MAKE_REQUEST });
axios
.get(SPACEX_URL, {
cancelToken: cancelToken1.token,
params: { ...params },
})
.then((res) => {
dispatch({ type: ACTIONS.GET_DATA, payload: { launches: res.data } });
})
.catch((e) => {
if (axios.isCancel(e)) return;
dispatch({ type: ACTIONS.ERROR, payload: { error: e } });
});
return () => cancelToken1.cancel();
}, [params]);
return state;
};
search-form.js:
const SearchForm = ({params, onParamChange}) => {
return (
<form className='search-form'>
<input
type='text'
placeholder='search for a launch'
className='search-form__field'
onChange={onParamChange}
name='name'
value={params.name || ''}
/>
</form>
);
};