Home > database >  How to check if a certain key name exist in json object in React app
How to check if a certain key name exist in json object in React app

Time:11-05

I create this custom hook in my React app. It should return a boolean.

const useFetchResponse = (url: string) => {
  const [isValid, setIsValid] = useState<boolean>(false);

  useEffect(() => {
    const fetchResponse = async () => {
      const response = await fetch(url);
      console.log(response);
      
      const obj = await response.json();

      if (response.ok) {
        console.log(await response.json());
        setIsValid(true);
      }

      return response;
    };

    fetchResponse().then((res) => res);
  }, []);

  return isValid;
};

export default useFetchResponse;

When I log const obj = await response.json(); it returns: {"keyName":"some=key"}.

How do I create a condition to check if response.json() has a key named keyName?

Is that for example console.log('keyName' in obj) // true? Do you see more things which I can improve and refactor?

CodePudding user response:

Let assume you get response as follow

let response = {
  a:'data1',
  b:'data2',
  c:'data3'
};

Then you can extract keys from object as below:

let keyOnly = Object.keys(response)); // output will be ["a","b","c"]

then you can check if your require value includes on above array or not as below: Assuming if you want to check if "b" is included or not

let checkKey = keyOnly.includes(b)

CodePudding user response:

if you want to check whether an object has a certain property or not, the in operator is fine.

const obj = { a: 1 };
'a' in obj // return true
'b' in obj // return false

About improvements

const [fetchState, setFetchState] = useState('pending');

  useEffect(() => {
    const fetchResponse = async () => {
      try {
        setFetchState('loading');
        const response = await fetch(url);
        console.log(response);
      
        const obj = await response.json();

        if (response.ok) {
          console.log(await response.json());
          setFetchState('success');
        }

        return response;
      } catch (error) {
        setFetchState('failed')
      }
      
    };

    fetchResponse().then((res) => res);
  }, []);

  return fetchState;
};

  • fetchResponse(); would be enough. fetchResponse().then((res) => res); is unnecessary.
  • [optional] You could use libraries to making requests, like an axios. That would be more convenient.

CodePudding user response:

in is slower than below way.

const isValid = obj[`keyname`] !== undefined

Check more detail in here

  • Related