Home > Back-end >  call the method of another class in a hooks
call the method of another class in a hooks

Time:09-06

hi everyone i have one question about react native. 1) How can I call another class inside a hooks? For example if I have:

import React, { Component, useEffect, useState} from 'react';
import { TextInput } from 'react-native-paper';
import {  View,Text} from 'react-native';
import Utils from './Utils';
export default function Userprofile() {
  const [text, setText] = useState("");
  const [sid, setSid] = useState("");

  useEffect(() => {
    var y = sid.getSid();
    setSid(t);
  }, []);
  return (
    <View>
      <TextInput label="" value={text} onChangeText={(text) => setText(text)} />
      <Text>il sid è: {sid}</Text>
    </View>
  );
}

and in Utils.js:

import React, { Component } from "react";
export default class Utils extends Component {
  constructor(props) {
    super(props);
  }
  async getSid() {
    try {
      var value = await AsyncStorage.getItem("sid");
      if (value !== null) {
        console.log("value second screen is:", value);
        return value;
      }
    } catch (error) {}
  }
  render() {}
}

how can I call the method of another class in a hooks?

CodePudding user response:

First of all you do not have defined any custom hook in your example. You have a functional component named UserProfile and a class component named Utils which does not render anything.

It seems to me that you want to call getSid in the useEffect located inside UserProfile. There is no reason to implement this function inside the class component Utils.

Instead, separate your business logic from your UI by introducing a new custom hook.

I will call this hook useUtils.

export function useUtils() {
    const [sid, setSid] = React.useState();

    React.useEffect(() => {
        const load = async () => {
          try {
              const value = await AsyncStorage.getItem("sid");
              if (value !== null) {
                 setSid(value);
              }
          } catch (error) {}
        }
        load();
    }, [])

   return {
       sid,
   }
}

Then, use it as usual.

export default function Userprofile() {
  const [text, setText] = useState("");
  const {sid} = useUtils();

  if (!sid) {
    return null;
  }

  return (
    <View>
      <TextInput label="" value={text} onChangeText={(text) => setText(text)} />
      <Text>il sid è: {sid}</Text>
    </View>
  );
}
  • Related