const [country, setCountry] = useState(""); const [city, setCity] = useState(""); const [population, setPopulation] = useState(""); const [location, setLocation] = useState(""); const [temp_min, setTmep_min] = useState("");Oye, alguien tiene alguna idea de cómo reemplazar estos ganchos useState de una manera efectiva y limpiar el código como ponerlos todos en un objeto en lugar de inicializarlo con el nuevo useState.
Puede usar useReducer en su lugar. Esto le permitiría inicializar el estado con un objeto. Además, ahora puede usar el dispatch para todas las actualizaciones, aunque deberá pasarle un objeto con la propiedad que desea actualizar.
const reducer = (state, update) => ({ ...state, ...update, }); const [state, dispatch] = useReducer({ country: '', city: '', population: '', location: '', temp_min: '' });Ejemplos:
dispatch({ country: 'Spain' }); // setting a country dispatch({ city: 'Madrid' }); // setting a cityPuedes hacer un useState como este
const [obj, setObj] = useState({ country: "", City: "", Population: "", Location: "", temp_min: "" })Implementé el gancho useReducer para poner todas estas propiedades en un objeto simple (que es mejor para componentes con estados complejos) y también usé algunas validaciones para evitar errores al actualizar el estado cuando el componente está desmontado, por ejemplo:
const App: React.FC = () => { const initialState = { name: '', password: '' }; const { state, onUpdateValue, // Update a value from the dictionary onClearValue // Remove a value from the dictionary onClear // Remove all values from the dictionary } = useDictionary(initialState); const onSubmit = useCallback((event: React.FormEvent) => { event.preventDefault(); console.log('Create User!', state); onClear(); }, [state]); return ( <form onSubmit={onSubmit}> <label> Name: <input type="text" value={state.name} onChange={(e) => onUpdateValue('name', e.target?.value)} /> </label> <label> Password: <input type="password" value={state.password} onChange={(e) => onUpdateValue('password', e.target?.value)} /> </label> <input type="submit" value="Submit" /> </form> ); }Link del repositorio: https://github.com/proyecto26/use-dictionary
¡Feliz codificación! <3