abbas derafshi
abbas derafshi

Reputation: 287

hooks not set state at first time

i beginner in react native, in my project i have search filed after press button user name and Authentication state not initialize my variable but after press for the second time my state initialize and show me data can help me to fix this. thanks

const DataFeatch = async () => {

await Authentication_Creator();

let SearchData = {
  "user_name": await UserName,
  "user_authentication": await User_Authentication,
};    
try {
  let response = await fetch('fechURL, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(SearchData),
  });
  let json = await response.json();
  if (json == 'no result') {
    something
  } else {
    SetDataSource(json);
  }
}
catch{
 ERRoR
}

}

and my Authentication_Creator is

  const Authentication_Creator = async () => {

var RNFS = require('react-native-fs');
var path = RNFS.DocumentDirectoryPath + 'path';
var data = await RNFS.readFile(path, 'utf8');
var mydata = await JSON.parse(data);
let hash = data;
hash = md5(hash);

SetUserName(() => mydata.UserName);
SetUser_Authentication(() => hash);

}

Upvotes: 1

Views: 130

Answers (1)

Fahad Mahmood
Fahad Mahmood

Reputation: 159

You have to make some changes in your code, you can't use await Username, it has no effect to react state.

You can change Authentication_Creator like this like this:

 const Authentication_Creator = async () => {

    var RNFS = require('react-native-fs');
    var path = RNFS.DocumentDirectoryPath + 'path';
    var data = await RNFS.readFile(path, 'utf8');
    var mydata = await JSON.parse(data);
    let hash = data;
    hash = md5(hash);

    return { user_name: myData.UserName, user_authentication: hash};

}

After that in your Data Fetch Function:

const DataFeatch = async () => {

let SearchData = await Authentication_Creator();

// and other code

}

Upvotes: 1

Related Questions