It is important to not fully trust the response you get back from your API. Validate the response with yup to ensure the data you are using is as you expect.
200
with invalid data. I had a great time.
Here is what I am talking about:
catch
will catch it. Otherwise, we’re all good. This doesn’t just happen with custom fetch
calls. In React, if you use a fetch hook, many times it will allow you to pass in generics (useFetch<Profile>()
) to say what the shape of the data will be. Again, this works, I do it, but there isn’t a lot of safety from incorrect data.
Idea: I have been thinking about is using a validation library, in this case yup to add a extra layer of protection (this idea will work with any validation library). Usually, if we’re working with forms we already have a validation library installed, so we aren’t really introducing extra dependencies into our project. Additionally, if you’re a Typescript user, these libraries can make type definitions a lot easier as well!
Looking at our example above, we need to introduce 2 extra things. One is our schema and the other is validating our json
.
profile
schema. Depending on how you like to structure your projects. This could be in a profile.schema.ts
or profile.model.ts
file. Allowing you to separate things a little easier.
profile
definition, we can validate our json
, and handle any ValidationError
that yup might throw.
validate
call is successful, then we can be confident that data
is in our Profile
shape.catch
block, we can now test for this ValidationError
and provide the user some extra details about the issue, instead of a generic ‘Something went wrong’ message.stripUnknown: true
to the validate
options. As the name suggests, it will remove any data that isn’t in our profile
schema. This makes the data more consistent but also ‘forces’ someone to update the schema if additional data is added.validation
option where you can do the same thing. Alternatively, I’ve seen that many allow for a transform
step. Giving you a chance to change the data before returning it to the user.
me
function and return some weird data to see if the validation works.
Peace! ✌️
Bit of a disclaimer: the ideas in this article are just ideas. I haven’t been able to test them out fully yet. Complex data structures or conditional responses might require a more complex schema. I have noticed with complex schemas that the InferType
becomes a “everything is optional” type, which isn’t always ideal.