I send a GET request and in response get a user object like this:
{
name: 'Alex',
email: '[email protected]',
age: 18,
}
then I need to set this object to the state and render data in some different components
interface User {
name: string | null,
email: string,
age: number,
}
const [user, setUser] = useState<User>();
const getUser = async () => {
const response = await API.getUserData();
setUser(response);
} catch (error) {
console.log(error)
}
The problem: For some reason name might be null and in this case I should render on a page default values. As far as I know it can be done in many ways. The most obvious one is with conditional statements like this:
<h1>{name ? name : 'Default value'}</h1>
or
<h1>{name ?? 'Default value'}</h1>
But for me its a bad option because too many conditions in many components. Is there a way to set a default values in getUser function? Eventually I want to have my components to be like this:
// if name is null then its equal to some default value otherwise it equals to the value from server.
<h1>{name}</h1>
CodePudding user response:
I think one option is transforming response before you invoke setUser
. Something like this
function transformUserData(userData) {
// make transformation and replacement on Default Values
}
const getUser = async () => {
const response = await API.getUserData();
const responseWithDefaultValues = transformUserData(response);
setUser(responseWithDefaultValues);
} catch (error) {
console.log(error)
}
CodePudding user response:
Yes, you can set your default values in useState
:
const [user, setUser] = setState<User>({
name: "default value",
email: "default email address",
age: 0
})
Then with API calls, it gets changes.
But there is an issue if the API response was {name: null}
, it's not back to default value. so you must destruct your response
and check the values before setUser
:
const getUser = async () => {
const response = await API.getUserData();
const {name, email, age} = response;
setUser({name: name || "default value", email: email, age: age});
} catch (error) {
console.log(error)
}
as a side note:
The proper syntax for short circuit is:
<div> {name && 'Default value'} </div>