I am learning react-hooks, I created a series of state variables using useState
, when trying to debug and see its value I find that React Developer Tool does not show the name assigned to the state variable but the text State, this is inconvenient as it is not possible to identify from the beginning which variable is the one that is tried to debug
Update 1
This is the current source code
import React, { useState, useEffect, Fragment } from "react";
function Main() {
const [data, setData] = useState({ hits: [] });
const [query, setQuery] = useState("redux");
const [url, setUrl] = useState(
"https://hn.algolia.com/api/v1/search?query=redux"
);
const [isLoading, setIsLoading] = useState(false);
const [isError, setIsError] = useState(false);
useEffect(() => {
const fetchData = async () => {
setIsError(false);
setIsLoading(true);
try {
const response = await fetch(url);
const json = await response.json();
setData(json);
} catch (e) {
setIsError(true);
}
setIsLoading(false);
};
fetchData();
}, [url]);
return (
<Fragment>
<form
onSubmit={event => {
setUrl(`http://hn.algolia.com/api/v1/search?query=${query}`);
event.preventDefault();
}}
>
<input value={query} onChange={event => setQuery(event.target.value)} />
<button type="submit">Search</button>
</form>
{isError && <div>Something went wrong ...</div>}
{isLoading ? (
<div>Loading...</div>
) : (
<ul>
{data.hits.map(item => (
<li key={item.objectID}>
<a href={item.url}>{item.title}</a>
</li>
))}
</ul>
)}
</Fragment>
);
}
export default Main;
I am getting this in React Developer tool
Updated 2
I am using Firefox 68
Is it possible that React Developer Tool shows the name of state variables created using useState
?
You can use useDebugValue
to display a custom label in your own hook:
const format = ({ label, value }) =>
label + ': ' + (typeof value === 'object' ? JSON.stringify(value) : value);
const useNamedState = (label, initialState) => {
const states = useState(initialState);
useDebugValue({ label, value: states[0] }, format);
return states;
};
const [name, setName] = useState('bob');
const [age, setAge] = useState(11);
const [address, setAddress] = useState('London, United Kingdom');
const [isVirgin, setIsVirgin] = useState(false);
const [isMale, setIsMale] = useState(true);
const [hobbies, setHobbies] = useState(['gaming', 'hiking', 'cooking']);
const [friendList, setFriendList] = useState(['bob']);
const [name, setName] = useNamedState('name', 'bob');
const [age, setAge] = useNamedState('age', 11);
const [address, setAddress] = useNamedState('address', 'London, United Kingdom');
const [isVirgin, setIsVirgin] = useNamedState('isVirgin', false);
const [isMale, setIsMale] = useNamedState('isMale', true);
const [hobbies, setHobbies] = useNamedState('hobbies', ['gaming', 'hiking', 'cooking']);
const [friendList, setFriendList] = useNamedState('friendList', ['bob']);