Search code examples
reactjstypescriptreact-nativetypesasyncstorage

Typescript/React-Native: Argument of type 'string | null' is not assignable to parameter of type 'SetStateAction<never[]>'


I am learning typescript with React-Native and I want to use AsyncStorage library. When setting my state after reading value from the storage, I got this problem:

const value: string | null Argument of type 'string | null' is not assignable to parameter of type 'SetStateAction<never[]>'. Type 'null' is not assignable to type 'SetStateAction<never[]>'

The App is showing the value but I want to learn how to solve the problem. I guess I have to assign a type to the useState, but do not know how to assign SetStateAction type.

How do I set the type to the useState to solve this problem?

This is the sample code:

import React, {useEffect, useState} from 'react';
import {Text, View} from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';

const App = () => {
  const [value, setValue] = useState([]);
  
  async function saveValue(key: string, value: string) {
    await AsyncStorage.setItem(key, value);
  }
  
  async function readValue(key: string) {
    const value = await AsyncStorage.getItem(key);
    setValue(value);
  }

  useEffect(() => {
    saveValue('123', 'Hello world! ');
    readValue('123');
  }, []);

  return (
    <View>
      <Text>{value}</Text>
    </View>
  );
};

export default App;


Thank you.


Solution

  • Using const [value,setValue] = useState<string | null>(''); fixed the issue as suggested by @Mic Fung. This is the resulting code:

    const App = () => {
      const [value, setValue] = useState<string | null>('');
        
    async function saveValue(key: string, value: string) {
        await AsyncStorage.setItem(key, value);
      }
    
    async function readValue(key: string) {
        const value = await AsyncStorage.getItem(key);
        setValue(value);
      }
    
      useEffect(() => {
        saveValue('123', 'Hello world! ');
        readValue('123');
      }, []);
    
      return (
        <View>
          <Text>{value}</Text>
        </View>
      );
    };
    
    
    

    Hello world!