0

I'm trying to use a fetched value from DB as a default value (shown until the component is clicked) of an input field.

However, using "defaultValue" attribute, the fetched value it is not displayed.

App.tsx file (value is fetched successfully):

  const [Income, setIncome] = useState<string>('0');

    useEffect(() => {

    const incomeResp = async () => {
      await axios.get('http://localhost:4000/app/income')
      .then(
        result => setIncome(result.data && result.data.length > 0 ? result.data[0].income : 0))
    }
    incomeResp();
  }, []);


  return (
      <div className="App">
        <div>
          <IncomeExpensesContainer 
            income={Income}
            setIncome={setIncome} 
            totalExpenses={TotalExpensesAmount} 
            currencySymbol={Currency}
          />
      </div>

Component's file:

interface Props {
    income: string;
    setIncome: (value: string) => void; 
    totalExpenses: number;
    currencySymbol: string;
}

const IncomeExpensesContainer: React.FC<Props> = ({
        income,
        setIncome, 
        totalExpenses, 
        currencySymbol,
    }: Props) => {


   const [insertedValue, setInsertedValue] = useState<string>(income);

return (
    <Grid container spacing={1} className="income-expenses-container">
        <InputItem 
            onChange={setInsertedValue}
            onBlur={setIncome}
            title="Income" 
            type="number" 
            placeholder="Your income" 
            defaultValue={income}
        />
    </Grid>
);

What am I missing here?

2
  • What is ur return statement in App? How do u pass the data to the components file? So many missing informations. Commented Jun 13, 2021 at 12:59
  • @Delice I've added return statement of the in App.tsx. What additional information is needed? Commented Jun 13, 2021 at 13:02

2 Answers 2

1

Edited after additional information provied

Use the passed prop in your component:

const Component = (props) => {
       return (
            <InputItem 
              onChange={setInsertedValue}
              onBlur={setIncome}
              title="Income" 
              type="number" 
              placeholder="Your income" 
              defaultValue={props.income}
        />
}
Sign up to request clarification or add additional context in comments.

5 Comments

Yes, this is what I'm doing (I've just updated the code in order to show that)
I think the problem is that defaultValue is initialized on first render on component. The first time you render the component - your state is probably empty. Can you try render your input component only if your state has value? E.g. {income && <IncomeExpensesContainer [...] /> and see what happens?
I've replaced defaultValue by value and it didn't help.
I've also added conditional rendering to this component {<stateThatChanges> && <IncomeExpensesContainer [...] />} and it works as expected - is rendered once the state changes, however, it's initial value = 0, so, the issue is not solved
I've finally figured out the solution: 1) created const [insertedValue, setInsertedValue] = useState(income); and assigned value={insertedValue} 2) used useEffect(() => { setInsertedValue(income) }, [income]);
0

To anyone who encounters this problem in the future, the solution that worked for me was to use the in-built type casting methods of javascript when passing number type values. This for example

const Component = (props) => {
       return (
            <InputItem 
              onChange={setInsertedValue}
              onBlur={setIncome}
              title="Income" 
              type="number" 
              placeholder="Your income" 
              defaultValue={props.income}
        />
}

when called should receive the defaultValue as

<InputItem 
        onChange={setInsertedValue}
        onBlur={setIncome}
        title="Income" 
        type="number" 
        placeholder="Your income" 
        defaultValue={income.toFixed(0)} // toString and toPrecision work as well 
    />

I think it is something taking place under the hood of the React Native TextInput component, though I don't have any resource justifying this.

Hope it helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.