Home > OS >  Allocating typesScript interface to store React useState array object returns undefined error
Allocating typesScript interface to store React useState array object returns undefined error

Time:08-03

Hi guys I'm new to TypeScript,

I'm trying to use an API to return a response payload which I am then setting as the state of my fishes array using useState hook and then using the state stored in that array to allocate data in my typesScript interface which can then be rendered in my react component using the interface object. But it renders an undefined error.

Following is the response payload being used to set the state of the fishes array

const [fishes, setFishes] = useState([])
useEffect(() => {
    FetchApiData(species).then(response => setFishes(response))
}, [])

I am allocating the index element from the useState array as follow:

let fishData = fishes[0]

I have a response payload in fishData as follows which has keys with spaces in them:

{
"Fishery Management": "<ul>\n<li><a href=\"https://www.fisheries.noaa.gov/region/southeast\">NOAA Fisheries</a> with the <a href=\"http://gulfcouncil.org/\">Gulf of Mexico</a> and <a href=\"http://safmc.net/\">South Atlantic</a> Fishery Management Councils manage red snapper in the United States.</li>\n<li>In the Gulf of Mexico, managed under the <a href=\"https://www.fisheries.noaa.gov/management-plan/gulf-mexico-reef-fish-fishery-management-plan\">Fishery Management Plan for the Reef Fish Resources of the Gulf of Mexico</a>:\n<ul>\n<li>A rebuilding plan was implemented in 2005&nbsp;with the goal of rebuilding the Gulf of Mexico red snapper stock by 2032.</li>\n<li>Annual catch limits for the commercial and recreational fisheries.</li>\n<li>Commercial fishermen must have a permit to harvest red snapper. Through the individual fishing quota (<a href=\"https://www.fisheries.noaa.gov/national/laws-and-policies/catch-shares\">catch shares</a>) program, they may harvest their quotas whenever they choose and must report how much they harvest.</li>\n<li>A minimum size limit protects the spawning stock and juveniles.</li>\n<li>For more information, visit <a href=\"https://www.fisheries.noaa.gov/southeast/sustainable-fisheries/gulf-mexico-recreational-red-snapper-management\">NOAA Fisheries Southeast Regional Office’s Gulf of Mexico Red Snapper Management</a> website.</li>\n</ul>\n</li>\n<li>In the South Atlantic, managed under the <a href=\"https://www.fisheries.noaa.gov/management-plan/south-atlantic-snapper-grouper-fishery-management-plan\">Fishery Management Plan for the Snapper-Grouper Fishery of the South Atlantic Region</a>:\n<ul>\n<li>A rebuilding plan was implemented in 2010 with the goal of rebuilding the South Atlantic red snapper stock by 2044. It allows for limited harvest of red snapper as the population continues to grow.&nbsp;</li>\n<li>In 2010 and 2011, regulations prohibited harvest of red snapper in the South Atlantic to protect the population from too much fishing pressure and to allow the number of fish to increase.</li>\n<li>Limited harvest was allowed in 2012-2014. Harvest was prohibited in 2015 and 2016.</li>\n<li>For more information, visit the <a href=\"http://safmc.net/regulations/regulations-by-species/red-snapper/\">South Atlantic Fishery Management Council’s Red Snapper Regulations</a> website or <a href=\"https://www.fisheries.noaa.gov/management-plan/south-atlantic-snapper-grouper-fishery-management-plan\">NOAA Fisheries Southeast Regional Office’s South Atlantic Snapper-Grouper Management</a> page.</li>\n</ul>\n</li>\n<li>State management consistency with federal management\n<ul>\n<li>In the Gulf of Mexico, recreational state management measures are very different from recreational federal management measures.</li>\n<li>In the South Atlantic, state management measures are fairly consistent with the federal management measures noted above. Some states, such as South Carolina and Georgia, automatically adopt federal regulations while others have separate regulations.</li>\n</ul>\n</li>\n</ul>\n",
"Habitat": "<ul>\n<li>Larval red snapper swim freely within the water column.</li>\n<li>Juveniles live in shallow waters over sandy or muddy bottom habitat.</li>\n<li>Adults live on the bottom, usually near hard structures on the continental shelf that have moderate to high relief (for example, coral reefs, artificial reefs, rocks, ledges, and caves), sloping soft-bottom areas, and limestone deposits.</li>\n</ul>\n",
"Habitat Impacts": "Fishing gear used to harvest red snapper has minimal impacts on habitat.",
"Image Gallery": [
    {
        "src": "https://origin-east-01-drupal-fishwatch.woc.noaa.gov/sites/default/files/snapperred_1.jpg",
        "alt": "Red snapper in Gray&#039;s Reef National Marine Sanctuary.",
        "title": "Red snapper in Gray&#039;s Reef National Marine Sanctuary."
    },
    {
        "src": "https://origin-east-01-drupal-fishwatch.woc.noaa.gov/sites/default/files/snapperred_2.jpg",
        "alt": " Removing a red snapper otolith (ear bone). Scientists determine the age of snapper by counting annual growth rings on their otoliths, similar to counting growth rings in trees.",
        "title": " Removing a red snapper otolith (ear bone). Scientists determine the age of snapper by counting annual growth rings on their otoliths, similar to counting growth rings in trees."
    },
    {
        "src": "https://origin-east-01-drupal-fishwatch.woc.noaa.gov/sites/default/files/snapperred_3.jpg",
        "alt": "A fisherman holds up his red snapper catch.",
        "title": "A fisherman holds up his red snapper catch."
    },
    {
        "src": "https://origin-east-01-drupal-fishwatch.woc.noaa.gov/sites/default/files/snapperred_4.jpg",
        "alt": "Whole red snapper. Photo credit: U.S. Food and Drug Administration",
        "title": "Whole red snapper. Photo credit: U.S. Food and Drug Administration"
    },
    {
        "src": "https://origin-east-01-drupal-fishwatch.woc.noaa.gov/sites/default/files/snapperred_7.jpg",
        "alt": "Red Snapper",
        "title": ""
    }
],
"Location": "<ul>\n<li>Red snapper are generally found at 30 to 620 feet deep in the Gulf of Mexico and along the eastern coasts of North America, Central America, and northern South America.</li>\n<li>They are rare north of the Carolinas.</li>\n</ul>\n",
"Management": null,
"NOAA Fisheries Region": "Southeast",
"Population": "Below target level in the Gulf of Mexico but fishing rate promotes population growth. Significantly below target population levels in the South Atlantic. Rebuilding plans are in place for both stocks.",
"Population Status": "<ul>\n<li>\n<p>There are two stocks of red snapper: The Gulf of Mexico stock and the South Atlantic stock. According to the most recent stock assessments:</p>\n<ul>\n<li>\n<p>The Gulf of Mexico stock is not overfished but still rebuilding to target levels (2018 stock assessment), and not subject to overfishing based on 2020 catch data.&nbsp; Summary stock assessment information can be found on <a href=\"https://www.st.nmfs.noaa.gov/stocksmart?stockname=Red snapper - Gulf of Mexico&amp;stockid=10230\">Stock SMART</a>.</p>\n</li>\n<li>\n<p>The South Atlantic stock is overfished and subject to overfishing (2021 stock assessment). Summary stock assessment information can be found on <a href=\"https://www.st.nmfs.noaa.gov/stocksmart?stockname=Red snapper - Southern Atlantic Coast&amp;stockid=10231\">Stock SMART</a>.</p>\n</li>\n</ul>\n</li>\n</ul>\n",
"Scientific Name": "Lutjanus campechanus",
"Species Aliases": "<a href=\"/species-aliases/snapper\" typeof=\"skos:Concept\" property=\"rdfs:label skos:prefLabel\" datatype=\"\">Snapper</a>, <a href=\"/species-aliases/genuine-red-snapper\" typeof=\"skos:Concept\" property=\"rdfs:label skos:prefLabel\" datatype=\"\">Genuine red snapper</a>, <a href=\"/species-aliases/american-reds\" typeof=\"skos:Concept\" property=\"rdfs:label skos:prefLabel\" datatype=\"\">American reds</a>, <a href=\"/species-aliases/spot-snapper\" typeof=\"skos:Concept\" property=\"rdfs:label skos:prefLabel\" datatype=\"\">Spot snapper</a>",
"Species Illustration Photo": {
    "src": "https://origin-east-01-drupal-fishwatch.woc.noaa.gov/sites/default/files/red_snapper.png",
    "alt": "",
    "title": ""
},
"Species Name": "Red Snapper",
"Animal Health": null,
"Availability": "<p>U.S. wild-caught red snapper is available fresh year-round.</p>\n",
"Biology": "<ul>\n<li>Red snapper grow at a moderate rate, and may reach 40 inches long and 50 pounds.</li>\n<li>They can live a long time—red snapper as old as 57 years have been reported in the Gulf of Mexico and as old as 51 years in the South Atlantic.</li>\n<li>Females are able to reproduce as early as age 2.</li>\n<li>Males and females spawn from May to October, depending on their location.</li>\n<li>Red snapper feed on fish, shrimp, crab, worms, cephalopods (octopus or squid), and some plankton (tiny floating plants and animals).</li>\n<li>Young red snapper are food for the large carnivorous fish that share their habitat, such as jacks, groupers, sharks, barracudas, and morays.</li>\n<li>Large marine mammals and turtles also eat snapper.</li>\n</ul>\n",
"Bycatch": "Regulations require modified fishing gear to reduce bycatch. Release techniques improve the chance of survival of unintentionally caught fish.",
"Calories": "100",
"Carbohydrate": "0 g",
"Cholesterol": "37 mg",
"Color": "<p>The meat is pinkish with yellow tones when raw and turns somewhat lighter when cooked. Red snapper have trademark red skin and red eyes and come from domestic fisheries. To aid in identification, they are usually sold with the skin on.</p>\n",
"Disease Treatment and Prevention": null,
"Diseases in Salmon": null,
"Displayed Seafood Profile Illustration": null,
"Ecosystem Services": null,
"Environmental Considerations": null,
"Environmental Effects": null,
"Farming Methods": null,
"Farming Methods_": null,
"Fat, Total": "1.34 g",
"Feeds_": null,
"Feeds": null,
"Fiber, Total Dietary": "0 g",
"Fishing Rate": "At recommended level in the Gulf of Mexico. Reduced to end overfishing in the South Atlantic.",
"Harvest": "<ul>\n<li>Commercial sector:\n<ul>\n<li>In 2020, commercial landings of red snapper totaled approximately 7.7 million pounds and were valued at $31.5 million,&nbsp;according to the NOAA Fisheries <a href=\"https://www.fisheries.noaa.gov/foss/f?p=215:200:14838376182170::NO:RP::\">commercial fishing landings database</a>.&nbsp;</li>\n</ul>\n</li>\n<li>Gear types, habitat impacts, and bycatch:\n<ul>\n<li>Commercial fishermen mainly use hook-and-line gear (handlines and electric reels) to harvest red snapper, and sometimes use longlines (in the Gulf of Mexico) and spears.</li>\n<li>Commercial fishermen using hook and line gear attach multiple hooks to a vertical line and weight it at the bottom.</li>\n<li>Recreational anglers primarily use hook and line gear to harvest red snapper.</li>\n<li>Fishermen are encouraged to use <a href=\"https://www.flseagrant.org/fisheries/venting/\" rel=\"external\">venting tools</a> and <a href=\"https://videos.fisheries.noaa.gov/detail/video/3619674964001/recompression-devices:-helping-anglers-fish-smarter?autoStart=true&amp;q=recompression devices\" rel=\"external\">recompression devices</a> when releasing fish suffering from barotrauma. Barotrauma occurs when the swim bladder of a fish expands as it is quickly brought to the surface. Venting tools help deflate the swim bladder and recompression devices help the fish return to the depth at which it was caught to recompress the air in the swim bladder, preventing serious injury to the fish.</li>\n<li>In the Gulf of Mexico:\n<ul>\n<li>Regulations prohibit fishing in certain areas of the Gulf of Mexico to protect sensitive fish populations and habitats.</li>\n<li>Measures are in place to reduce sea turtle bycatch by longline gear and include limiting times or areas where fishermen can fish, gear restrictions, and a limit on the number of vessels that can participate in the reef fish fishery. &nbsp;In addition, all commercial fishermen must follow special sea turtle release protocols and have specialized gear to improve the chances of incidentally caught sea turtles to survive.</li>\n</ul>\n</li>\n<li>In the South Atlantic:\n<ul>\n<li>Circle hooks are required when fishing for snapper and grouper species north of latitude 28° N. De-hooking devices are also required in the South Atlantic for snapper-grouper species.</li>\n<li>Measures are in place to reduce sea turtle bycatch by fishing gear and include gear restrictions and handling requirements, and a limit on the number of vessels that can participate in the snapper-grouper fishery.</li>\n</ul>\n</li>\n</ul>\n</li>\n<li>\n<p>Recreational sector:</p>\n<ul>\n<li>\n<p>Recreational anglers primarily use hook and line gear to harvest red snapper.</p>\n</li>\n<li>\n<p>In 2020, recreational anglers landed approximately 14.9 million pounds of red snapper, according to the NOAA Fisheries <a href=\"https://www.fisheries.noaa.gov/foss/f?p=215:200:13795838889086::NO:RP::\">recreational fishing landings database</a>.&nbsp;</p>\n</li>\n<li>\n<p>In the Gulf of Mexico:</p>\n<ul>\n<li>\n<p>Red snapper must be a minimum size to be caught, and there is a limit on how many red snapper anglers can keep per day.</p>\n</li>\n<li>\n<p>Charter vessels and headboats must have a permit to fish in federal waters.</p>\n</li>\n<li>\n<p>For-hire vessels must use specialized gear and follow certain sea turtle release protocols.</p>\n</li>\n</ul>\n</li>\n<li>In the South Atlantic:\n<ul>\n<li>In 2012, 2013, and 2014 the red snapper season was limited.</li>\n<li>In 2010–2011 and 2015–2016, the red snapper fishery was closed.</li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n",
"Harvest Type": "Wild",
"Health Benefits": "<p>Red snapper is low in saturated fat and sodium and is a very good source of protein.</p>\n",
"Human_Health_": null,
"Human Health": null,
"Physical Description": "<ul>\n<li>Red snapper in deeper waters tend to be redder than those caught in shallower waters.</li>\n<li>They have a long triangular face with the upper part sloping more strongly than the lower.</li>\n<li>Their jaws are equal, with the lower one sometimes slightly projecting.</li>\n<li>They have enlarged canine teeth, which is why they are called “snappers.”</li>\n</ul>\n",
"Production": null,
"Protein": "20.51 g",
"Quote": "U.S. wild-caught red snapper is a smart seafood choice because it is sustainably managed under rebuilding plans that allow limited harvest by U.S. fishermen.",
"Quote Background Color": "#ab4946",
"Research": "<ul>\n<li>Scientists from <span><a href=\"https://www.sefsc.noaa.gov/\">NOAA Fisheries Southeast Fisheries Science Center</a>&nbsp;</span>monitor the abundance of red snapper stocks. Scientists, managers, and stakeholders assess the status of these stocks through the <a href=\"http://sedarweb.org/\" target=\"_blank\">Southeast Data, Assessment, and Review</a> (SEDAR) process.</li>\n<li>Using data from the Southeast Reef Fish Survey, NMFS researchers and partners recently identified the spawning season and several spawning locations for red snapper along the southeastern United States.&nbsp; This research is described in the open access journal <a href=\"http://journals.plos.org/plosone/article?id=10.1371/journal.pone.0172968\">PLoS ONE</a>, and was also adapted for schools in <a href=\"http://www.sciencejournalforkids.org/science-articles/how-can-we-protect-fish-better\">The Science Journal for Kids</a>.</li>\n</ul>\n",
"Saturated Fatty Acids, Total": "0.285 g",
"Selenium": "38.2 mcg",
"Serving Weight": "100 g (raw)",
"Servings": "1",
"Sodium": "64 mg",
"Source": "<p>U.S. wild-caught from North Carolina to Texas.</p>\n",
"Sugars, Total": "0 g",
"Taste": "<p>Red snapper has a sweetly mild but distinctive flavor.</p>\n",
"Texture": "<p>Red snapper is semi-firm, lean, and moist.</p>\n",
"Path": "/profiles/red-snapper",
"last_update": "02/17/2022 - 19:11"

}

I have an interface as follows which I am using to hold values returned from the payload:

interface fishDetails{
    fishName?: string | null | undefined
}

const fishInfo : fishDetails = {
    fishName: fishData['Species Name']
}

I then want to use fishInfo to allocate values to be used in my react functional component as follows:

 return (
    <div className="App">
        <h1>{fishInfo.fishName}</h1>
    </div>
);

It returns the following undefined error in the console: Undefined error

undefined error

What am I doing wrong?

CodePudding user response:

On the first render, fishes is [], so fishes[0] is undefined. The useEffect() then initiates your fetch request. When that resolves and calls setFishes(), React triggers a re-render in which fishes is set to response.

You should use an optional chaining operator to prevent a TypeError when attempting to access any property of fishData, which is potentially undefined as established above:

const fishInfo : fishDetails = {
    fishName: fishData?.['Species Name']
}
  • Related