Home > database >  React Native promise pass the value to variable as string
React Native promise pass the value to variable as string

Time:02-23

I am new to React Native. I have to create a promise and be able to get the response data.

export async function findColor() {
    
        try{
            const token = await AsyncStorage.getItem('token');
            const id = await AsyncStorage.getItem('id');

            const resp = (
                await api(token).get(`api/blockgroup/getList`)
            ).data;
           
            const retVal = '"'   resp.data[0].template.mcolor  '"';
            
            console.log (typeof retVal, retVal, 'retvalue');
       
            return retVal;
        }
        catch(err){
            return {
                error: true,
                code: err.request.status,
            };
        }
    }

But when I called the function I get something like this

{"_U": 0, "_V": 0, "_W": null, "_X": null}

I found out that I can access the value by using .then() as I tried to printout the value to console:

findColor().then(response => console.log(response));

I got the string value

"#0eade1"

But I don't know how can I pass the value to a variable as a string? Let's say I want to create a variable color and pass the value "#0eade1" to it. How can I do that?

I really appreciate if anyone can help me. Thanks!

EDIT: i just want to make this clear. i need to pass the value only as string because i need to pass it to another module from import. i have config module where i need to change my theme color with the value from hook i called. thats config will only accept string object, and i don't know if i should use react native component in config module.

CodePudding user response:

You could create a hook that handles that. Consider the following snippet.

export function useColor() {
    const [color, setColor] = useState()

    React.useEffect(() => {

        // you should add your function in here
        findColor().then(response => setColor(response))

    }, [])
    
    return {
        color,
    }
}

Then use your hook in your screen, whenever you need color.


const TestScreen = () => {

    // color can used however you like
    const {color} = useColor()
}

CodePudding user response:

You should try this by this you can use this as normal function call.

export async function findColor() {
            const token = await AsyncStorage.getItem('token');
            const id = await AsyncStorage.getItem('id');
            api(token).get(`api/blockgroup/getList`)
            .then(resp=>{
              const retVal = '"'   resp.data[0].template.mcolor  '"';
            
              console.log (typeof retVal, retVal, 'retvalue');
       
              return retVal;
            });
            .catch((err){
            return {
                error: true,
                code: err.request.status,
            };
        })
    }
  • Related