Cannot get program to run. (Javascript, HTML, CSS) - javascript

I am trying to write a simple text based rpg for my little nephew. I followed along with a youtube tutorial and for some reason I cannot understand, the program won't run. I've gone over the code in all three files several times for typo's and anything obscure that shouldn't be there. However, I am stumped. Any help would be appreciated.
const textElement = document.getElementById("text")
const optionButtonsElement = document.getElementById("option-buttons")
let state = {}
function startGame(){
state = {}
showTextNode(1)
}
function showTextNode(textNodeIndex){
const textNode = textNodes.find(textNode => textNode.id === textNodeIndex)
textElement.innerText = textNode.text
while (optionButtonsElement.firstChild){
optionButtonsElement.removeChild(optionButtonsElement.firstChild)
}
textNode.options.forEach(option => {
if(showOption(option)){
const button = document.createElement("button")
button.innerText = option.text
button.classList.add("btn")
button.addEventListener("click", () => selectOption(option))
optionButtonsElement.appendChild(button)
}
})
}
function showOption(option) {
return option.requiredState == null || option.requiredState(state)
}
function selectOption(option) {
const nextTextNodeId = option.nextText
state = object.assign(state, option.setState)
if (nextTextNodeId <= 0){
return startGame()
}
state = Object.assign(state, option.State)
showTextNode(nextTextNodeId)
}
const textNodes = [
{
id: 1,
text: "You wake up in a strange place and you see a jar of blue goo near you.",
options: [
{
text: "Take goo",
setState: {bluegoo: true},
nextText: 2
},
{
text: "Leave the goo",
nextText: 2
}
]
},
{
id: 2,
text: "You venture forth in search of answers to where you are when you come across a merchant.",
options:[
{
text: "Trade the goo for a sword.",
requiredState: (currentState) => currentState.bluegoo,
setState: {bluegoo: false, sword: true },
nextText: 3
},
{
text: "Trade the goo for a shield.",
requiredState: (currentState) => currentState.bluegoo,
setState: {bluegoo: false, shield: true },
nextText: 3
},
{
text: "Ignore the merchant.",
nextText: 3
},
]
},
{
id: 3,
text: "After leaving the merchant you start to feel tired ans tumble upon a small town next to a dangerous looking castle.",
options: [
{
text: "Explore the castle.",
nextText: 4
},
{
text: "Find a room to sleep at in the towwn.",
nextText: 5
},
{
text: "Find some hay in a stable to sleep in.",
nextText: 6
}
]
},
{
id: 4,
text: "You are so tired that you fall asleep while exploring the castle and are killed by some terrible monster in your sleep.",
options [
{
text: "Restart",
nextText: -1
}
]
},
{
id: 5,
text: 'Without any money to buy a room you break into the nearest inn and fall asleep. After a few hours of sleep the owner of the inn finds you and has the town guard lock you in a cell.',
options: [
{
text: 'Restart',
nextText: -1
}
]
},
{
id: 6,
text: 'You wake up well rested and full of energy ready to explore the nearby castle.',
options: [
{
text: 'Explore the castle',
nextText: 7
}
]
},
{
id: 7,
text: 'While exploring the castle you come across a horrible monster in your path.',
options: [
{
text: 'Try to run',
nextText: 8
},
{
text: 'Attack it with your sword',
requiredState: (currentState) => currentState.sword,
nextText: 9
},
{
text: 'Hide behind your shield',
requiredState: (currentState) => currentState.shield,
nextText: 10
},
{
text: 'Throw the blue goo at it',
requiredState: (currentState) => currentState.blueGoo,
nextText: 11
}
]
},
{
id: 8,
text: 'Your attempts to run are in vain and the monster easily catches.',
options: [
{
text: 'Restart',
nextText: -1
}
]
},
{
id: 9,
text: 'You foolishly thought this monster could be slain with a single sword.',
options: [
{
text: 'Restart',
nextText: -1
}
]
},
{
id: 10,
text: 'The monster laughed as you hid behind your shield and ate you.',
options: [
{
text: 'Restart',
nextText: -1
}
]
},
{
id: 11,
text: 'You threw your jar of goo at the monster and it exploded. After the dust settled you saw the monster was destroyed. Seeing your victory you decide to claim this castle as your and live out the rest of your days there.',
options: [
{
text: 'Congratulations. Play Again.',
nextText: -1
}
]
}
]
startGame()
*, *::before, *::after{
box-sizing: border-box;
font-family: Gotham Rounded;
}
body{
padding: 0;
margin: 0;
display: flex;
justify-content: center;
align-items: center;
width: 100vw;
height: 100vh;
background-color: #333;
}
.container{
width: 800px;
max-width: 80%;
background-color: white;
padding: 10px;
border-radius: 5px;
box-shadow: 0 0 10px 2px;
}
.btn-grid{
display: grid;
grid-template-columns: repeat(2, auto);
gap: 10px;
margin-top: 20px;
}
.btn{
background-color: hsl(200, 100%, 50%);
border: 1px solid hsl(200, 100%, 30%);
border-radius: 5px;
padding: 5px 10px;
color: white;
outline: none;
}
.btn:hover{
border-color: black;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sawyer's Dungeons and Dragons Game</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<script src="game.js"></script>
</head>
<body>
<div class="container">
<div id="text">Text</div>
<div id="option-buttons" class="btn-grid">
<button class="btn">Option 1</button>
<button class="btn">Option 2</button>
<button class="btn">Option 3</button>
<button class="btn">Option 4</button>
</div>
</div>
</body>
</html>
I appreciate anyone taking a look at this.
Cheers!

There are few mistakes in your code
1st:
You are missing : here
{
id: 4,
text: "You are so tired that you fall asleep while exploring the castle and are killed by some terrible monster in your sleep.",
// : is missing after options
options [
{
text: "Restart",
nextText: -1
}
]
},
2nd:
It should be Object.assign and NOT
state = object.assign(state, option.setState)
function selectOption(option) {
const nextTextNodeId = option.nextText
// It should be Object.assign
state = object.assign(state, option.setState)
if (nextTextNodeId <= 0){
return startGame()
}
state = Object.assign(state, option.State)
showTextNode(nextTextNodeId)
}
You should add defer attribute while linking js file in html file in this case
<script defer src="game.js"></script>
This should fix the problem
HTML File
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sawyer's Dungeons and Dragons Game</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
// need to add defer attribute
<script defer src="game.js"></script>
</head>
<body>
<div class="container">
<div id="text">Text</div>
<div id="option-buttons" class="btn-grid">
<button class="btn">Option 1</button>
<button class="btn">Option 2</button>
<button class="btn">Option 3</button>
<button class="btn">Option 4</button>
</div>
</div>
</body>
</html>
JS File
const textElement = document.getElementById("text")
const optionButtonsElement = document.getElementById("option-buttons")
let state = {}
function startGame(){
state = {}
showTextNode(1)
}
function showTextNode(textNodeIndex){
const textNode = textNodes.find(textNode => textNode.id === textNodeIndex)
textElement.innerText = textNode.text
while (optionButtonsElement.firstChild){
optionButtonsElement.removeChild(optionButtonsElement.firstChild)
}
textNode.options.forEach(option => {
if(showOption(option)){
const button = document.createElement("button")
button.innerText = option.text
button.classList.add("btn")
button.addEventListener("click", () => selectOption(option))
optionButtonsElement.appendChild(button)
}
})
}
function showOption(option) {
return option.requiredState == null || option.requiredState(state)
}
function selectOption(option) {
const nextTextNodeId = option.nextText
state = Object.assign(state, option.setState)
if (nextTextNodeId <= 0){
return startGame()
}
state = Object.assign(state, option.State)
showTextNode(nextTextNodeId)
}
const textNodes = [
{
id: 1,
text: "You wake up in a strange place and you see a jar of blue goo near you.",
options: [
{
text: "Take goo",
setState: {bluegoo: true},
nextText: 2
},
{
text: "Leave the goo",
nextText: 2
}
]
},
{
id: 2,
text: "You venture forth in search of answers to where you are when you come across a merchant.",
options:[
{
text: "Trade the goo for a sword.",
requiredState: (currentState) => currentState.bluegoo,
setState: {bluegoo: false, sword: true },
nextText: 3
},
{
text: "Trade the goo for a shield.",
requiredState: (currentState) => currentState.bluegoo,
setState: {bluegoo: false, shield: true },
nextText: 3
},
{
text: "Ignore the merchant.",
nextText: 3
},
]
},
{
id: 3,
text: "After leaving the merchant you start to feel tired ans tumble upon a small town next to a dangerous looking castle.",
options: [
{
text: "Explore the castle.",
nextText: 4
},
{
text: "Find a room to sleep at in the towwn.",
nextText: 5
},
{
text: "Find some hay in a stable to sleep in.",
nextText: 6
}
]
},
{
id: 4,
text: "You are so tired that you fall asleep while exploring the castle and are killed by some terrible monster in your sleep.",
options: [
{
text: "Restart",
nextText: -1
}
]
},
{
id: 5,
text: 'Without any money to buy a room you break into the nearest inn and fall asleep. After a few hours of sleep the owner of the inn finds you and has the town guard lock you in a cell.',
options: [
{
text: 'Restart',
nextText: -1
}
]
},
{
id: 6,
text: 'You wake up well rested and full of energy ready to explore the nearby castle.',
options: [
{
text: 'Explore the castle',
nextText: 7
}
]
},
{
id: 7,
text: 'While exploring the castle you come across a horrible monster in your path.',
options: [
{
text: 'Try to run',
nextText: 8
},
{
text: 'Attack it with your sword',
requiredState: (currentState) => currentState.sword,
nextText: 9
},
{
text: 'Hide behind your shield',
requiredState: (currentState) => currentState.shield,
nextText: 10
},
{
text: 'Throw the blue goo at it',
requiredState: (currentState) => currentState.blueGoo,
nextText: 11
}
]
},
{
id: 8,
text: 'Your attempts to run are in vain and the monster easily catches.',
options: [
{
text: 'Restart',
nextText: -1
}
]
},
{
id: 9,
text: 'You foolishly thought this monster could be slain with a single sword.',
options: [
{
text: 'Restart',
nextText: -1
}
]
},
{
id: 10,
text: 'The monster laughed as you hid behind your shield and ate you.',
options: [
{
text: 'Restart',
nextText: -1
}
]
},
{
id: 11,
text: 'You threw your jar of goo at the monster and it exploded. After the dust settled you saw the monster was destroyed. Seeing your victory you decide to claim this castle as your and live out the rest of your days there.',
options: [
{
text: 'Congratulations. Play Again.',
nextText: -1
}
]
}
]
startGame()

Have you opened your browser's console to check for errors?
text: "You are so tired that you fall asleep while exploring the castle and are killed by some terrible monster in your sleep.",
options [
You are missing a ":" here:
options: [
As for this:
state = object.assign(state, option.setState)
What is object?

Related

JQuery quiz app not resetting to show the next answer

I have a math app in JavaScript/JQuery, there will be a timer that gives the user 3 seconds to answer math questions given to them at random, if they don't answer in 3 seconds the user will lose. I can't get the next random question to display when the user selects the right answer.
I put all of the questions in an array of objects. Then I created a function that takes a random Math function as the parameter. The random function randomly picks between the indices in the array of objects.
I thought by calling this random function again in my selectAnswer() that it would reset the information fr the current question and display the next question at random. But it's only appending the current question again..
I am a beginner so my code might not be th greatest! I'm open to any insight!!
You'll also notice, that the event to reload the page when the start over button is clicked is not firing correctly. I'm working on that.
const questions = [
{
question: '80 * 20',
answ: 80 * 20,
answers: [
{ text: 1600 },
{ text: -1600 },
{ text: 16 },
{ text: 160 },
]
},
{
question: '80 / 20',
answ: 80 / 20,
answers: [
{ text: '-4', correct: false },
{ text: '50', correct: false },
{ text: '4', correct: true },
{ text: '40', correct: false },
]
},
{
question: '80 + 20',
answ: 80 + 20,
answers: [
{ text: '-100', correct: false },
{ text: '1000', correct: false },
{ text: '10', correct: false },
{ text: '100', correct: true },
]
},
{
question: '80 - 20',
answ: 80 - 20,
answers: [
{ text: '66', correct: false },
{ text: '60', correct: true },
{ text: '600', correct: false },
{ text: '20', correct: false },
]
},
{
question: '8 * -2',
answ: 8 * -2,
answers: [
{ text: '66', correct: false },
{ text: '666', correct: false },
{ text: '-16', correct: true },
{ text: '16', correct: false },
]
},
{
question: '-2 + 8',
answ: -2 + 8,
answers: [
{ text: '-6', correct: false },
{ text: '66', correct: false },
{ text: '600', correct: false },
{ text: '6', correct: true },
]
},
{
question: '14 - 66',
answ: 14 - 66,
answers: [
{ text: '52', correct: false },
{ text: '54', correct: false },
{ text: '-52', correct: true },
{ text: '-54', correct: false },
]
},
{
question: '103 * 33',
answ: 103 * 33,
answers: [
{ text: '3502', correct: true },
{ text: '3509', correct: false },
{ text: '3503', correct: false },
{ text: '3507', correct: false },
]
},
{
question: '165 / 33',
answ: 165 / 33,
answers: [
{ text: '33', correct: true },
{ text: '15', correct: false },
{ text: '5', correct: false },
{ text: '25', correct: false },
]
},
{
question: '88 * 28',
answ: 88 * 28,
answers: [
{ text: '2624', correct: false },
{ text: '2462', correct: false },
{ text: '2464', correct: true },
{ text: '2426', correct: false },
]
}
]
$(() => {
// GRABBING HTML ELEMENTS
const $startBtn = $("#start-btn")
const $timeLeft = $("#time-left")
const $quitBtn = $("#quit-btn")
const $secondsLeft = $("#seconds-left")
const $questionContainerElement = $("#question-container")
const $questionElement = $("#question")
const $answerButtonElement = $("#answer-buttons")
$secondsLeft.hide()
$quitBtn.hide()
let $buttons;
let mathAnsw;
// CREATING VARIABLES FOR RANDOM FUNCTION ANCD URRENT QUESTION
let shuffledQuestions, currentQuestionIndex
let timeLeft = 3
// START BUTTON FUNCTIONALITY
// HIDES START MENU WHEN FIRED
// INVOKES RANDOM FUNCTION
$startBtn.click(() => {
$secondsLeft.fadeIn(900)
$quitBtn.fadeIn(900)
$startBtn.fadeOut(900)
// countDown()
console.log("started")
$startBtn.hide()
// SORTS THROUGH THE ARRAY OF QUESTIONS
shuffledQuestions = questions.sort(() => Math.random() - .5)
currentQuestionIndex = 0;
$questionContainerElement.show()
showQuestion(shuffledQuestions[currentQuestionIndex])
mathAnsw = questions[currentQuestionIndex].answ
console.log("the answer", mathAnsw)
})
// NEXT BUTTON FUNCTIONALITY
// INVOKES SHOWQUESTION() EVERYTIME FIRED
const setNext = () => {
showQuestion(question)
console.log(questions)
// resetState()
}
$quitBtn.click(() => {
location.reload(true)
})
// CURRENT QUESTION
// APPEND CURRENT QUESTION TO THE QUESTION BOX
const showQuestion = (question) => {
$questionElement.append(`<h2 class="text-center">${questions[currentQuestionIndex].question}</h2>`)
console.log(questions[currentQuestionIndex].question)
// POPULATING ANSWERS
const AnswersArray = question.answers
let value
for (x in AnswersArray) {
$buttons = $(`<button id="answer${x}"class="btn" value='${questions[currentQuestionIndex].answers[x].text}'>${questions[currentQuestionIndex].answers[x].text}</button>`)
$answerButtonElement.append($buttons)
}
selectAnswer()
}
// ANSWER
const selectAnswer = () => {
$('.btn').each(function () {
$(this).on("click", function () {
let $value = $(this).attr('value')
let value = Number($value)
console.log(value)
console.log(mathAnsw)
if (value === mathAnsw) {
console.log('correct!!')
showQuestion(shuffledQuestions[currentQuestionIndex])
} else {
$("#question-container").replaceWith("<h1>You Lost</h1>")
$quitBtn.replaceWith("<button id='start-over'>Start Over</button>")
console.log("wrong")
}
})
})
}
$("#start-over").click(() => {
location.reload(true)
console.log("clicked")
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fast Math</title>
<link rel="stylesheet" href="index.css">
<script src="../fast-math/lib/jquery-3.6.0.min.js"></script>
</head>
<body>
<div class="container">
<h3 id="seconds-left">Seconds Left: <span id="time-left"></span></h3>
<div id="question-container" class="hide">
<div id="question">Question</div>
<div id="answer-buttons" class="btn-grid">
</div>
</div>
<div class="controls">
<button id="start-btn" class="start-btn btn">start</button>
<button id="quit-btn" class="quit-btn btn">quit</button>
</div>
</div>
<script src="index.js"></script>
<script src="mathProblems.js"></script>
</body>
</html>

How do I adapt a javascript to use a database input?

I am a novice Java/CSS/HTML user with a background using SQL. For a personal website project, I want to connect a webpage i am building to a database list of questions. Currently, the questions I am using are just written in the javacode like such:
const questions = [{
question: 'What is 2 + 2?',
answers: [
{ text: '4', correct: true },
{ text: '22', correct: false },
{ text: '2.2', correct: false },
{ text: '57', correct: false }
]
},
{
question: 'What is the captial of Russia?',
answers: [
{ text: 'Helsinki', correct: false },
{ text: 'St Petersburg', correct: false },
{ text: 'Moscow', correct: true },
{ text: 'Sainsburys', correct: false }
]
},
{
question: 'How many sides does a nonagon have',
answers: [
{ text: 'As many as it wants', correct: false },
{ text: 'Nine', correct: true },
{ text: 'Seven', correct: false },
{ text: 'Twelve', correct: false }
]
},
{
question: 'What is 4 * 2?',
answers: [
{ text: '6', correct: false },
{ text: '8', correct: true },
{ text: '10', correct: false },
{ text: '12', correct: false }
]
}
]
Instead of using this hideous list, I would like to use a connection to information I have in a amazon-DynamoDB database which has 50 or so questions listed.
My question is:
What would replace the code above to create a connection to the database and to use the new data the same way?
I can reformat the sql database data to have columns: Question, Answer, Correct? in preperation
Any help would be fantastic, I've gone a bit off grid from the training material I was using!
removed question about looking for a database recommendation

SweetAlert - Change modal color

By default the colour is white.
Is it possible to change modal background color of sweetalert2?
I have tried it to change with CSS, as I follow on the other question here and here, like this :
.sweet-alert
{
background-color: #2f2f2f96;
}
but I got nothing,
i use the sweetalert question feature
Swal.mixin({
input: 'text',
confirmButtonText: 'Next →',
showCancelButton: true,
progressSteps: ['1', '2', '3']
}).queue([
{
title: 'Question 1',
text: 'Chaining swal2 modals is easy'
},
'Question 2',
'Question 3'
]).then((result) => {
if (result.value) {
Swal.fire({
title: 'All done!',
html:
'Your answers: <pre><code>' +
JSON.stringify(result.value) +
'</code></pre>',
confirmButtonText: 'Lovely!'
})
}
})
I wish i can change the modal colour to grey
You have to add background in Swal function. It will Works for you.
Swal.mixin({
input: "text",
confirmButtonText: "Next →",
showCancelButton: true,
background: 'gray',
progressSteps: ["1", "2", "3"]
})
.queue([
{
title: "Question 1",
text: "Chaining swal2 modals is easy"
},
"Question 2",
"Question 3"
])
.then(result => {
if (result.value) {
Swal.fire({
title: "All done!",
background: 'gray',
html:
"Your answers: <pre><code>" +
JSON.stringify(result.value) +
"</code></pre>",
confirmButtonText: "Lovely!"
});
}
});

Don't understand why my last item is undefined

I'm trying to order different job with their status, name, description and color.
I don't understand why my last item (color and ame is undefined while the other item are good...
(example in the last part) .
I'm using a array and display thanks to the function.
Thanks for your help.
var type = new Array("blue", "yellow", "red", "notbuilt");
var numberThingparkx = new Array(0, 0, 0, 0);
var reds = new Array();
function Thingparkx(response){
var Json = JSON.parse(response);
if(Json.jobs){
var Data = Json.jobs.map(function(i) {
var url = i.url.split('//');
ajaxGet("https://"+AuthString+url[1]+"api/json", Thingparkx);
});
}else{
for(var i = 0; i < type.length; i++){
if(type[i] == Json.color){
numberThingparkx[i]++;
if(Json.color === "red"){
nom = new Array(Json.fullDisplayName,Json.description,"error",Json.color);
reds.push(nom);
}
if(Json.color === "yellow"){
nom = new Array(Json.fullDisplayName,Json.description,"instable",Json.color);
reds.push(nom);
}
}
}
}
}
var Data = reds.map(function(i) {
return {
"title": {
"text": i[0]
},
"label": {
"name": i[2],
"color": i[3],
},
"description": i[1]
};
});
console.log(Data);
push({
key: '186163-f7e58b30-8a01-0137-f3a4-0af8bc3cd516',//Widget Key
data: Data
})
.then(response => console.log(response));
}
Actual result :
[ { title: { text: 'Thingpark-X » tpx-integration-tests build' },
label: { name: 'error', color: 'red' },
description: 'Job for tpx-integration-tests build' },
{ title: { text: 'Thingpark-X » Bundles » util build' },
label: { name: 'error', color: 'red' },
description: 'Job for util build' },
{ title:
{ text: 'Thingpark-X » Bundles » storage.driver.mongodb build' },
label: { name: 'instable', color: 'yellow' },
description: 'Job for storage.driver.mongodb build' },
{ title:
{ text: 'Thingpark-X » Platforms » CI » tpx create accounts' },
label: { name: undefined, color: undefined },
description: 'Job for tpx create accounts' } ]
Expected result:
[ { title: { text: 'Thingpark-X » tpx-integration-tests build' },
label: { name: 'error', color: 'red' },
description: 'Job for tpx-integration-tests build' },
{ title: { text: 'Thingpark-X » Bundles » util build' },
label: { name: 'error', color: 'red' },
description: 'Job for util build' },
{ title:
{ text: 'Thingpark-X » Bundles » storage.driver.mongodb build' },
label: { name: 'instable', color: 'yellow' },
description: 'Job for storage' },
{ title:
{ text: 'Thingpark-X » Platforms » CI » tpx create accounts' },
label: { name: 'error', color: 'red' },
description: 'Job for tpx create accounts' } ]

nested const JSX

I think this is a weird question but i have a variable in React native like this :
const phrases = {
Default: {
title: "Fetching the Weather",
subtitle: "Be patient, you're witnessing a miricle",
highlight: "Fetching",
color: "#636363",
background: "#9C9C9C",
},
Clear: {
title: "It's Amazing Balls",
subtitle: "Rock that shit!",
highlight: "Amazing",
color: "#E32500",
background: "#FFD017",
},
Rain: {
title: "Rain rain please go away",
subtitle: "Stay inside and code all day",
highlight: "away",
color: "#004A96",
background: "#2F343A",
},
Thunderstorm: {
title: "Thunder Strike",
subtitle: "Unplug those devices",
highlight: "Thunder",
color: "#FBFF46",
background: "#020202",
},
Clouds: {
title: "Cloud storage limit reached",
subtitle: "error: 5000 - cirrocumulus",
highlight: "limit",
color: "#0044FF",
background: "#939393",
},
Snow: {
title: "Brain Freeze",
subtitle: "You're not supposed to eat it",
highlight: "Brain",
color: "#021D4C",
background: "#15A678",
},
Drizzle: {
title: "Meh... don't even ask",
subtitle: "What did I just say?",
highlight: "don't",
color: "#B3F6E4",
background: "#1FBB68",
},
Mist: {
title: "Mist title",
subtitle: "Mist sub",
highlight: "Mist",
color: "#B3F6E4",
background: "#1FBB68",
},
}
now when i am trying to access Title like this :
phrases[this.state.weather].title
I get this error :
undefined is not an object (evaluating'phrases[this.state.weather].title')
any one can help with this ??
Code like this phrases['Clear'].title works well. So, the only reason why your code phrases[this.state.weather].title doesn't work - your this.state.weather is undefined
You should check that the given weather is a valid weather for phrases
const phrases = {
Default: {
title: "Fetching the Fucking Weather",
subtitle: "Be patient, you're witnessing a miricle",
highlight: "Fucking",
color: "#636363",
background: "#9C9C9C",
},
Clear: {
title: "It's Fucking Amaze Balls",
subtitle: "Rock that shit!",
highlight: "Fucking",
color: "#E32500",
background: "#FFD017",
},
Rain: {
title: "Rain rain please go away",
subtitle: "Stay inside and code all day",
highlight: "away",
color: "#004A96",
background: "#2F343A",
},
Thunderstorm: {
title: "Fucking Thunder Strike",
subtitle: "Unplug those devices",
highlight: "Thunder",
color: "#FBFF46",
background: "#020202",
},
Clouds: {
title: "Cloud storage limit reached",
subtitle: "error: 5000 - cirrocumulus",
highlight: "limit",
color: "#0044FF",
background: "#939393",
},
Snow: {
title: "Brain Fucking Freeze",
subtitle: "You're not supposed to eat it",
highlight: "Fucking",
color: "#021D4C",
background: "#15A678",
},
Drizzle: {
title: "Meh... don't even ask",
subtitle: "What did I just say?",
highlight: "don't",
color: "#B3F6E4",
background: "#1FBB68",
},
Mist: {
title: "Mist title",
subtitle: "Mist sub",
highlight: "Mist",
color: "#B3F6E4",
background: "#1FBB68",
},
};
function phraseExists(name) {
return Object.prototype.hasOwnProperty.call(phrases, name);
}
function getDefaultPhrase() {
return phrases.Default;
}
function getPhrase(name) {
console.log(`Does "${name}" exist?`, phraseExists(name));
return phraseExists(name) ? phrases[name] : null;
}
function getPhraseOrDefault(name) {
return getPhrase(name) || getDefaultPhrase();
}
getPhrase('Foo'); // false
getPhrase('Mist'); // true
It is quite likely that your component's this.state.weather has value undefined or something else unexpected. This kind of things should always be splitted in production code, so I recommend you to first get the object from phrases:
let phraseObj = this.state.weather ? phrases[this.state.weather] : undefined;
Then continue by checking if the value exists:
let result = phraseObj && phraseObj.title || 'No weather title found';
Yeah... so I guess there is something else not working that is not shown in the code shared here. I hope you find the real issue soon. :)

Categories

Resources