简体   繁体   中英

How do i return an object from my react state

I am trying to find an item from a collection, from the code below, in order to update my react component, the propertState object isnt empty, it contains a list which i have console logged, however I seem to get an underfined object when i console log the value returned from my findProperty function... I am trying update my localState with that value so that my component can render the right data.

    const PropertyComponent = () => {
        const { propertyId } = useParams();
    
        const propertyState: IPropertiesState = useSelector(
            propertiesStateSelector
        );
    
        const[property, setProperty] = useState()
    
        const findProperty = (propertyId, properties) => {
            let propertyReturn;
            for (var i=0; i < properties.length; i++) {
                if (properties[i].propertyId === propertyId) {
                    propertyToReturn = properties[i];
                    break;
                }
            }
            setProperty(propertyReturn)
            return propertyReturn;
        }
    
        const foundProperty = findProperty(propertyId, propertyState.properties);
    
        return (<>{property.propertyName}</>)
    }

export default PropertyComponent

There are a few things that you shall consider when you are finding data and updating states based on external sources of data --useParams--

I will try to explain the solution by dividing your code in small pieces

    const PropertyComponent = () => {
        const { propertyId } = useParams();

Piece A: Consider that useParams is a hook connected to the router, that means that you component might be reactive and will change every time that a param changes in the URL. Your param might be undefined or an string depending if the param is present in your URL

const propertyState: IPropertiesState = useSelector(
            propertiesStateSelector
        );

Piece B: useSelector is other property that will make your component reactive to changes related to that selector. Your selector might return undefined or something based on your selection logic.

const[property, setProperty] = useState()

Piece C: Your state that starts as undefined in the first render.

So far we have just discovered 3 pieces of code that might start as undefined or not.

const findProperty = (propertyId, properties) => {
            let propertyReturn;
            for (var i=0; i < properties.length; i++) {
                if (properties[i].propertyId === propertyId) {
                    propertyToReturn = properties[i];
                    break;
                }
            }
            setProperty(propertyReturn)
            return propertyReturn;
        }
    
        const foundProperty = findProperty(propertyId, propertyState.properties);

Piece D: Here is when more problems start appearing, you are telling your code that in every render a function findProperty will be created and adding some internal dependencies with the setter of your state --setProperty--.

I would suggest to think about the actions that you want to do in simple steps and then you can understand where each piece of code belongs to where.

Let's subdivide this last piece of code --Piece D-- but in steps, you want to:

  1. Find something.
  2. The find should happen if you have an array where to find and a property.
  3. With the result I want to notify my component that something was found.

Step 1 and 2 can happen in a function defined outside of your component:

const findProperty = (propertyId, properties) => properties.find((property) => property.propertyId === propertyId)

NOTE: I took the liberty of modify your code by simplifying a little bit your find function.

Now we need to do the most important step, make your component react at the right time

const findProperty = (propertyId, properties) => properties.find((property) => property.propertyId === propertyId)

const PropertyComponent = () => {
        const { propertyId } = useParams();
    
        const propertyState: IPropertiesState = useSelector(
            propertiesStateSelector
        );
         
        const[property, setProperty] = useState({ propertyName: '' }); // I suggest to add default values to have more predictable returns in your component

        /**
         * Here is where the magic begins and we try to mix all of our values in a consistent way (thinking on the previous pieces and the potential "undefined" values) We need to tell react "do something when the data is ready", for that reason we will use an effect
         */

        useEffect(() => {
          // This effect will run every time that the dependencies --second argument-- changes, then you react afterwards.
          if(propertyId, propertyState.properties) {
              const propertyFound = findProperty(propertyId, propertyState.properties);
              if(propertyFound){ // Only if we have a result we will update our state.
                setProperty(propertyFound);
              }
          }
        }, [propertyId, propertyState.properties])
 

        return (<>{property.propertyName}</>)
    }

export default PropertyComponent

I think that in this way your intention might be more direct, but for sure there are other ways to do this. Depending of your intentions your code should be different, for instance I have a question:

What is it the purpose of this component? If its just for getting the property you could do a derived state , a little bit more complex selector. EG

function propertySelectorById(id) {
   return function(store) {
      const allProperties = propertiesStateSelector(store);
      const foundProperty = findProperty(id, allProperties);
      if( foundProperty ) {
         return foundProperty;
      } else {
         return null; // Or empty object, up to you
      }
   }
}

Then you can use it in any component that uses the useParam, or just create a simple hook . EG


function usePropertySelectorHook() {
   const { propertyId } = useParams();
   const property = useSelector(propertySelectorById(propertyId));

   return property;
}

And afterwards you can use this in any component


functon AnyComponent() {
  const property = usePropertySelectorHook();

  return <div> Magic {property}</div>
}

NOTE: I didn't test all the code, I wrote it directly in the comment but I think that should work.

Like this I think that there are even more ways to solve this, but its enough for now, hope that this helped you.

do you try this:

const found = propertyState.properties.find(element => element.propertyId === propertyId);
setProperty(found);

instead of all function findProperty

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM