Holiday Notice: Support will be provided on a limited scale from December 24th, 2024, to January 2nd, 2025. Happy holidays and a wonderful New Year!


Topic: Infinite loop when setting state as object from MDBSelect getValue()

web_ntx premium asked 3 years ago


Expected behavior

Set an object as the state using the return from <MDBSelect getValue()>

Actual behavior

Setting an object as the state triggers an infinite re-render loop. It works normally if a single value is set as the state instead of an object.

Resources (screenshots, code snippets etc.)

import React, { useState } from 'react';
import { MDBSelect } from 'mdb-react-ui-kit';

export default function TestComponent() {
  const [obj, setObj] = useState({});

  const handleChange = (e) => {
    setObj({ foo: e }); // triggers infinite re-render
    // this works however: setObj(e);
    console.log(obj);
  };
  return (
    <div className='mt-5 d-flex justify-content-center'>
      <MDBSelect
        data={[
          { text: 'One', value: 1 },
          { text: 'Two', value: 2 },
          { text: 'Three', value: 3 }
        ]}
        getValue={(e) => handleChange(e)}
      />
    </div>
  );
}

Krzysztof Wilk staff answered 3 years ago


Hi!

Thanks for reporting that. I'm glad you found the solution to that problem. We'll check it and try to fix it as soon as possible :)

Keep coding!


web_ntx premium answered 3 years ago


Here is a solution for future reference:

import React, { useState, useEffect } from 'react';
import { MDBSelect } from 'mdb-react-ui-kit';

export default function TestComponent() {
  const [val, setVal] = useState();
  const [obj, setObj] = useState({});

  useEffect(() => {
    setObj({ text: val });
    console.log(val);
  }, [val]);

  return (
    <div className='mt-5 d-flex justify-content-center'>
      <MDBSelect
        data={[
          { text: 'One', value: 1 },
          { text: 'Two', value: 2 },
          { text: 'Three', value: 3 },
        ]}
        getValue={(foo) => setVal(foo)}
      />
    </div>
  );
}


Please insert min. 20 characters.

FREE CONSULTATION

Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.

Status

Answered

Specification of the issue

  • ForumUser: Premium
  • Premium support: Yes
  • Technology: MDB React
  • MDB Version: MDB5 1.0.0-beta6
  • Device: PC
  • Browser: Chrome
  • OS: Windows 10
  • Provided sample code: Yes
  • Provided link: No