Unable to locate the variable named setState

Having trouble creating a toggle button that changes icon and color when clicked? I'm following a tutorial but encountered an issue.

Despite attempting different modifications, the same error persists: "Cannot Find Variable: setState"

Variable Error Link

The snippet of code causing the problem:

import { View, Text, StyleSheet ,Image, TouchableOpacity } from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import { Caption } from "react-native-paper"

const FlagSection = (props) => {

    const state = {
        heartIcon: "ios-heart-outline",
        liked: false
    }

    const toggleLike = () => {
        setState({
            liked: !state.liked
        })

        if(state.heartIcon){
            setState({
                heartIcon: "ios-heart"
            })
        }else{
            setState({
                heartIcon: "ios-heart-outline"
            })
        }
    }

    return (
        <View style={ styles.container }>
            <View style={ {flex:1} }>
            
                <View style= {styles.flagInfo}>
                    <View style= {styles.imageContent}>
                        <Image
                            source={ props.detail.flag }
                            size={60}
                        />

                        <View style= {styles.currencyContent}>
                            <Text> {props.detail.abbreviation} </Text>
                            <Caption style={ styles.caption }> {props.detail.name} </Caption>
                        </View>

                        <View style= {styles.likeButton}>
                            <TouchableOpacity onPress={ toggleLike }>
                                <Icon name={state.heartIcon} size={40} style={{color: state.heartIcon === "ios-heart-outline" ? "black" : "red"}}/>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
            
            </View>
        </View>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    flagInfo: {
        paddingLeft: 20,
        borderWidth: 5,
    },
    imageContent: {
        flexDirection: "row",
        marginTop: "3%",
    },
    currencyContent: {
        marginLeft: "3%",
        flexDirection: "column"
    },
    caption: {
        fontSize: 16,
        paddingTop: "3%",
        lineHeight: 14,
    },
    likeButton: {
        flexDirection: "row",
        justifyContent: "flex-end",
        marginLeft: "auto"
    }
});

export default FlagSection;

Answer №1

It is important to establish the initial state using useState within a functional component:

const [state, setState] = useState({
    heartIcon: "ios-heart-outline",
    liked: false
});

Subsequently, if you wish to update specific properties without erasing the others, you can spread the current state:

setState({
    ...state,
    liked: !state.liked
})

However, I recommend separating out the properties into distinct stateful variables instead:

const [heartIcon, setHeartIcon] = useState('ios-heart-outline');
const [liked, setLiked] = useState(false);

This way, you only need to utilize something like setLiked(!liked) without the need to manage transferring previous values within the same state variable.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Validate whether the path parameter in NextJS is null or empty before executing the query

Currently seeking a method to determine if the query value is empty using the path parameter approach. Have a file named pages/search/[variable1].js Below is the code snippet: import { useRouter } from "next/router" const Variable= () => { ...

The functionality of using multiple inputs with Google Places API is not functioning as expected

Having trouble with the Google Place API. I am unable to set up 2 input fields with autocomplete. The first input is populated from a payload received from the backend, while the second input is within a Bootstrap modal. I have tried various solutions fou ...

Django enables anonymous Ajax requests to reach a Generic View

Here is the current progress I have made: from django.views.generic import View from django.views.decorators.csrf import csrf_exempt class ConfigurationView(View): @csrf_exempt def dispatch(self, *args, **kwargs): return super(Configurati ...

The import of a package installed from git is not possible with Webpack

After forking a package in git and making my changes, I proceeded to install it using the following command in my terminal: npm install --save git+https://github.com/hayk94/ddp.js.git Once installed, I attempted to import the package in my code with this ...

After the click event, the variable in the Angular .ts file does not get refreshed

Great! I have a service in my .ts component that loops through an array of court names. Every time I click on a next or back arrow event, a counter is incremented starting at 0, where index 0 corresponds to field 1 and so on. The issue I'm facing is ...

Personalized Jasmine matchers for a Protractor/WebDriverJS component

Greetings fellow developers, I'm looking to create a custom matcher for Protractor/WebDriverJS element. Can anyone assist in improving my current code? Here is what I aim to include in the specs files: var button = element(by.tagName('button&a ...

Securing Routes with Firebase User Authentication in ReactJS

Currently, I am encountering an issue with the auth.onAuthStateChanged function in my Firebase user authentication service integrated with ReactJS. The function fires after the component has already been rendered, causing problems with redirecting users to ...

What is the best way to title an uploaded chunk with HTML5?

Here is the script I am working with: function upload_by_chunks() { var chunk_size = 1048576; // 1MB function slice(start, end) { if (file.slice) { return file.slice(start, end); } else if (file.webkitSlice) { ...

Socket.io functionality confirmed on desktop versions of Safari and Chrome, however not functioning properly on mobile devices

I have successfully set up communication between my server and HTML5 client using socket.io. It works perfectly on desktop and Safari on the iPhone simulator. However, when I try to run it on any iOS or Android device, the client fails to establish a conne ...

What seems to be the problem at hand, and where exactly is the issue located?

import React from 'react'; const card = ({name, email, id}) => { return( <div className='tc bg-light-green dib br3 ma2 grow bw2 shadow-5'> <img alt="robots" src = {'https://uniqueimage. ...

Tips for arranging alternating elements in a column layout using an array data model

In the $scope there is a dynamic array and in the HTML template, there are three columns. The goal is to render elements from the array in the HTML like this: <div class="first-column"> <div><!--element of (index + 3) % 3 === 0 will be pl ...

How can we use forEach on an array or JSON data while sorting by the most recent date?

How can I reverse the order of data in the "forEach" loop so that the latest date is displayed first instead of the oldest to newest? var json = { // JSON data goes here } json.TrackingRecord.MovementInformation.Movement.reverse().forEach(function(it ...

Foreground Service with Notification Channel for Android Oreo

My question pertains to starting a foreground service in Android 8 and understanding how foreground services interact with the notification channel system. Imagine we initiate a foreground service, followed by creating the necessary notification and linki ...

Transform a Javascript string or array into a JSON object

One of my challenges involves a JavaScript variable that contains values separated by commas, such as value1,value2,value3, ......,valueX, I am looking to transform these values into a JSON object. Ultimately, I plan on utilizing this object to compare ag ...

What is the method for displaying the name of a JSON property?

I am trying to work with a JSON in a specific format: { "nm_questionario":{"isEmpty":"MSGE1 - Nome do Question&aacute;rio"}, "ds_questionario":{"isEmpty":"MSGE1 - Descri&ccedil;&atilde;o do Question&aacute;rio"}, "dt_inicio_vigencia":{" ...

Arranging by upcoming birthday dates

Creating a birthday reminder app has been my latest project, where I store names and birthdays in JSON format. My goal is to display the names sorted based on whose birthday is approaching next. Initially, I considered calculating the time until each pers ...

avoiding the duplication of effects on an object when new objects are added via ajax

Currently, I am facing a minor issue with an application that I am working on. The problem arises on a particular page where the user can edit a document by dragging modules onto the canvas area. Upon loading the page, JavaScript causes the modules to be ...

Disable form input fields while keeping all other elements enabled

Currently, I am facing a dilemma where I must deactivate specific input fields within a form. Given that there are numerous fields to consider, individually disabling each one seems impractical. Can anyone offer advice on how to disable a set of elements ...

AngularJS directive facing a callback problem

Having trouble with callbacks while calling a service function This is the function defined in registrationService function checkUserAccess(incentiveLevel, callback, displayRegistrationView) { var url = "..."; httpWrapperService. ...

Deploy a web application using JavaScript and HTML to Heroku platform

I noticed that when I visit the Heroku dashboard, there is an option to create an app using Node.js, but not JavaScript. This raises a question for me - if I want to upload my locally created JavaScript/HTML5 app to Heroku, do I need to select Node.js or ...